gpt4 book ai didi

javascript - if如何将数组中的所有元素移动到底部?

转载 作者:行者123 更新时间:2023-11-28 16:48:38 29 4
gpt4 key购买 nike

如果数组(对象)的元素没有日期字段,如何将数组中的所有元素移动到底部?

let records = [{"id": 1}, {"id": 2, "date": new Date()}];

return records.sort(function(a: any, b: any) {
return a.hasOwnProperty('date')
? -1
: b.hasOwnProperty('date')
? 1
: 0;
});

所以我需要对所有带有日期的元素进行排序,并将其他没有日期的元素放置在列表底部。

最佳答案

您可以通过检查增量来检查不需要的内容并将其移动到底部。

const
getISO = d => d instanceof Date
? d.toISOString()
: d;

let records = [{ id: 1 }, { id: 2, date: new Date('2020-01-01') }, { id: 3 }, , { id: 2 }, { id: 4, date: new Date }];

records.sort((a, b) =>
Number('date' in b) - Number('date' in a) ||
getISO(b.date || '').localeCompare(getISO(a.date || ''))
);

console.log(records);

关于javascript - if如何将数组中的所有元素移动到底部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60241263/

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