我得到了一个对象列表,其中一些作为日期属性 completedAt
,但其中一些没有。我想要列表中最先完成的对象,那些没有 completedAt
属性的对象我想最后出现,我不关心它们的顺序,只要它们在后面标有日期的对象。
const list = [
{
id: '40',
completedAt: '2019-08-06T09:50:39.219Z'
},
{
id: '45'
},
{
id: '73',
completedAt: '2018-08-06T09:51:19.362Z'
},
{
id: '74',
completedAt: '2019-08-06T09:51:00.279Z'
},
{
id: '96',
completedAt: '2019-08-06T09:51:12.761Z'
}
];
const sortedList = list.sort((a, b) => { return new Date (b.completedAt) - new Date (a.completedAt) });
console.log(sortedList)
此函数确实对列表的顺序做了一些处理,但它们没有正确排序。
仅供引用,如果您知道任何 ramda 技巧,我也可以使用 Ramda.js,非常欢迎他们?
最佳答案
您可以检查真实性并按字符串对日期进行排序,因为您已经 ISO 8601日期字符串。
顺便说一句,Array#sort
sorts in situ(就地)。
const list = [{ id: '40', completedAt: '2019-08-06T09:50:39.219Z' }, { id: '45' }, { id: '73', completedAt: '2018-08-06T09:51:19.362Z' }, { id: '74', completedAt: '2019-08-06T09:51:00.279Z' }, { id: '96', completedAt: '2019-08-06T09:51:12.761Z' }];
list.sort((a, b) =>
!a.completedAt - !b.completedAt ||
b.completedAt.localeCompare(a.completedAt)
);
console.log(list);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于Javascript:按日期字符串属性对对象列表进行排序,其中日期可以是未定义的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57375035/