我有下面的数组
var dic = [
{user:'John', notifications:[{created: 'Wed Jan 12 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
{user:'Bob', notifications:[{created: 'Wed Jan 01 2023 11:58:24 GMT+0200 (Israel Standard Time)'},
{created: 'Wed Feb 01 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
{user:'Ron', notifications:[{created: 'Wed Jan 01 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
{user:'xxx', notifications:[{created: 'Wed Jan 31 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
]
我的目标是按日期对所有通知进行排序-最终结果应该如下所示-“Bob”应该是第一个,因为他获得了更高的日期(2月15日)
var dic = [
{user:'Bob', notifications:[{created: 'Wed Jan 01 2023 11:58:24 GMT+0200 (Israel Standard Time)'},
{created: 'Wed Feb 15 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
{user:'John', notifications:[{created: 'Wed Jan 12 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
{user:'Bob', notifications:[{created: 'Wed Jan 01 2023 11:58:24 GMT+0200 (Israel Standard Time)'},
{created: 'Wed Feb 01 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
{user:'Ron', notifications:[{created: 'Wed Jan 01 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
]
我试着像示例中那样对它进行排序-但我没有成功。
var dic = [
{user:'John', notifications:[{created: 'Wed Jan 12 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
{user:'Bob', notifications:[{created: 'Wed Jan 01 2023 11:58:24 GMT+0200 (Israel Standard Time)'}, {created: 'Wed Feb 15 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
{user:'Ron', notifications:[{created: 'Wed Jan 01 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
{user:'xxx', notifications:[{created: 'Wed Jan 31 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
]
dic.sort((a,b) => {
//console.log('a', a, 'b', b);
if(a.notifications.length > 1){
const test = a.notifications.reduce((a,b) => new Date(a.created).getTime() >= new Date(b.created).getTime() ? a.created : b.created);
return new Date(test).getTime() >= new Date(b.notifications[0].created).getTime() ? -1 : 1;
} else{
return new Date(a.notifications[0].created).getTime() <= new Date(b.notifications[0].created).getTime() ? -1 : 1;
}
})
console.log(dic)
2条答案
按热度按时间ilmyapht1#
这看起来像您希望的那样工作:
只需从每个对象获取日期,不需要
if
。laawzig22#