我无法按日期对数组进行排序。我尝试了很多不同的东西,但无法让它发挥作用。数组由具有 last_updated
字段的对象组成,该字段的值格式如下:24/1/2021 @ 13:21:2
。
我在执行 .map()
之前尝试对数组进行排序:
chats.sort(function (a, b) {
return (
new Date(b.last_update) - new Date(a.last_update)
);
});
这行不通,老实说我不知道为什么。这是因为日期中的 @
吗?
答案 0 :(得分:0)
试试这个:
chats.sort(function (a, b) {
return new Date(b.last_update).getTime() - new Date(a.last_update).getTime();
});
答案 1 :(得分:0)
const chats = [
{ title: 'Hiking', last_updated: new Date('2019-06-28') },
{ title: 'Shopping', last_updated: new Date('2019-06-10') },
{ title: 'Trekking', last_updated: new Date('2019-06-22') }
]
const sorted = chats.sort((a, b) => b.last_updated - a.last_updated)
console.log(sorted);
答案 2 :(得分:0)
是的,这是因为您无法使用 new Date
解析格式化的日期。如果您尝试解析它们,24/1/2021 @ 13:21:2
和 24/1/2021 13:21:2
都会返回无效日期。
您可以更新存储这些日期的方式,也可以在尝试排序之前解析日期。如果您不能以不同的格式(例如 ISO 8601)存储它们,我可能会使用 date-fns/parse
使用自定义格式化程序解析日期。请参见下面的示例:
import parse from 'date-fns/parse'
const chats = [
{ message: 'facilis consectetur, error sequi excepturi', last_updated: '24/1/2021 @ 13:21:2' },
{ message: 'sit amet consectetur adipisicing elit', last_updated: '24/1/2021 @ 13:20:14' },
{ message: 'mollitia unde fugiat delectus sunt ducimus', last_updated: '24/1/2021 @ 13:22:4' }
]
const format = 'd/M/y @ H:m:s'
const parseDate = d => parse(d, format, new Date())
chats.sort((a, b) => parseDate(b.last_updated) - parseDate(a.last_updated))
// it returns the following array:
//
// [
// {last_updated: "24/1/2021 @ 13:22:4", message: "mollitia unde fugiat delectus sunt ducimus"},
// {last_updated: "24/1/2021 @ 13:21:2", message: "facilis consectetur, error sequi excepturi"},
// {last_updated: "24/1/2021 @ 13:20:14", message: "sit amet consectetur adipisicing elit"}
// ]