gpt4 book ai didi

javascript - 如何对再次保存对象数组的对象数组进行排序

转载 作者:行者123 更新时间:2023-12-03 01:34:28 24 4
gpt4 key购买 nike

如何对再次保存对象数组的对象数组进行排序,并且我想按它们的最后时间戳对其进行排序。

 var weather = [{
city: 'New York',
status: 1,
response: [{
name: 'Example', lastTimestamp: '2017-12-19T12:43:14.000Z',
name: 'Example2', lastTimestamp: '2017-12-19T12:42:14.000Z'
}]
},
{
city: 'Chicago',
status: 1,
response: [{
name: 'Example', lastTimestamp: '2018-05-10T09:00:00.000Z',
name: 'Example2', lastTimestamp: '2018-05-10T09:04:00.000Z'
}]
}
]

作为返回,我想要像这样的排序对象

 var weather = [
{
city: 'Chicago',
status: 1,
response: [{
name: 'Example', lastTimestamp: '2018-05-10T09:00:00.000Z',
name: 'Example2', lastTimestamp: '2018-05-10T09:04:00.000Z'
}]
},
{
city: 'New York',
status: 1,
response: [{
name: 'Example', lastTimestamp: '2017-12-19T12:43:14.000Z',
name: 'Example2', lastTimestamp: '2017-12-19T12:42:14.000Z'
}]
}
]

最佳答案

这可能有用。它按城市名称排序,如果相等,则按lastTimestamp排序。

var weather = [
{
city: 'New York', status: 1, response: {name: 'Example', lastTimestamp: '2017-12-19T12:43:14.000Z'}
},
{
city: 'Chicago', status: 1, response: {name: 'Example', lastTimestamp: '2018-05-10T09:00:00.000Z'}
},
{
city: 'New York', status: 1, response: {name: 'Example', lastTimestamp: '2017-12-20T12:43:14.000Z'}
},
{
city: 'Chicago', status: 1, response: {name: 'Example', lastTimestamp: '2018-05-09T09:00:00.000Z'}
}
];

weather.sort(function(a,b){
return a.city>b.city ? 1 :
a.city<b.city ? -1 : new Date(a.response.lastTimestamp)-new Date(b.response.lastTimestamp)
})

console.log(weather);

关于javascript - 如何对再次保存对象数组的对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51134891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com