首页 > 解决方案 > 按字符串日期对对象数组进行排序

问题描述

我有一组如此结构化的对象。

let array = [
    {date: "22/03/2021 17:57", y: 10, type: "dil"},
    {date: "22/03/2021 17:58", y: 1, type: "dil"},
    {date: "15/04/2021 14:52", y: 3, type: "dil"},
    {date: "24/03/2021 14:52", y: 4, type: "dil"},
    {date: "01/04/2021 14:52", y: -2, type: "spp"},
    {date: "24/03/2021 14:53", y: -5, type: "spp"},
    {date: "18/04/2021 16:28", y: 3, type: "spp}
]

我必须按日期对其进行排序,但我不知道该怎么做,因为日期是一个字符串,如果我使用排序方法

array.sort((a,b) => (a.x > b.x) ? 1 : ((b.x > a.x) ? -1 : 0))

它是根据前两个字符排序的,而不是通过面对年、月、日、小时和分钟来正确排序。

有任何想法吗?我敢肯定这很容易,但我很困惑。

标签: javascriptarrayssorting

解决方案


您可以创建一个ISO 8601日期字符串并按字符串排序。

const
    getISO = string => string.replace(/(..)\/(..)\/(....) (..):(..)/, '$3-$2-$1 $4:$5'),
    array = [{ date: "22/03/2021 17:57", y: 10, type: "dil" }, { date: "22/03/2021 17:58", y: 1, type: "dil" }, { date: "15/04/2021 14:52", y: 3, type: "dil" }, { date: "24/03/2021 14:52", y: 4, type: "dil" }, { date: "01/04/2021 14:52", y: -2, type: "spp" }, { date: "24/03/2021 14:53", y: -5, type: "spp" }, { date: "18/04/2021 16:28", y: 3, type: "spp" }];

array.sort((a, b) => getISO(a.date).localeCompare(getISO(b.date)));

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读