我有一个这样的数组:
array = [
{
"title": "a",
"date": "2021-10-25T18:00:00.000"
},
{
"title": "b",
"date": "2021-10-20T18:00:00.000"
},
{
"title": "b",
"date": "2021-10-28T18:00:00.000"
},
{
"title": "b",
"date": "2021-10-30T18:00:00.000"
},
{
"title": "b",
"date": "2021-10-26T18:00:00.000"
}
]
我想先对今天最近的对象进行排序。我尝试过排序,但我觉得,我没有好的方法来做到这一点。
这是我尝试过的:
array.sort((a, b) => {
return (new Date(b.battle_start) > new Date()) - (new Date(a.battle_start) < new Date())
})
这就是我想要的
array = [
{
"title": "b",
"date": "2021-10-26T18:00:00.000"
},
{
"title": "a",
"date": "2021-10-25T18:00:00.000"
},
{
"title": "b",
"date": "2021-10-28T18:00:00.000"
},
{
"title": "b",
"date": "2021-10-30T18:00:00.000"
},
{
"title": "b",
"date": "2021-10-20T18:00:00.000"
}
]
您的代码可以适应使用Math.abs
,因此到过去或未来的距离将以相同的方式考虑:
const array = [{"title": "a","date": "2021-10-25T18:00:00.000"},{"title": "b","date": "2021-10-20T18:00:00.000"},{"title": "b","date": "2021-10-28T18:00:00.000"},{"title": "b","date": "2021-10-30T18:00:00.000"},{"title": "b","date": "2021-10-26T18:00:00.000"}];
let now = Date.now();
array.sort((a,b) =>
Math.abs(Date.parse(a.date) - now) - Math.abs(Date.parse(b.date) - now)
);
console.log(array);
您应该可以通过:
array.sort((a, b) => {
return (Math.abs(new Date(a.battle_start) - new Date())) - Math.abs((new Date(b.battle_start) - new Date()))
})
你要比较的是"now"和目标日期。