Javascript-按日期然后按时间对对象数组进行排序

时间:2018-08-09 02:28:26

标签: javascript arrays typescript sorting

我有以下数组:

[{id: 1, value : "value1", date: "2018-08-08", time: "15:27:17"},
{id: 2, value : "value2", date: "2018-08-09", time: "12:27:17"},
{id: 3, value : "value3", date: "2018-08-10", time: "17:27:17"},
{id: 4, value : "value4", date: "2018-08-11", time: "10:27:17"}]

如何对数组进行从最早到最新的排序,反之亦然?

我尝试按日期排序,但按时间排序将记录id 4的顺序交换为id 3,因为它的时间值早于记录3,但从技术上讲,它是较晚的。

鉴于此数组和json结构,如何对数组进行排序以同时考虑两个字段(datetime)?

1 个答案:

答案 0 :(得分:5)

date中的差异进行排序,如果没有差异,请通过单个time函数按.sort中的差异进行排序:

const arr = [{id: 1, value : "value1", date: "2018-08-08", time: "15:27:17"},
{id: 2, value : "value2", date: "2018-08-09", time: "12:27:17"},
{id: 3, value : "value3", date: "2018-08-10", time: "17:27:17"},
{id: 4, value : "value4", date: "2018-08-10", time: "01:27:17"},
{id: 5, value : "value5", date: "2018-08-10", time: "09:27:17"},
{id: 6, value : "value6", date: "2018-08-10", time: "23:27:17"},
{id: 7, value : "value7", date: "2018-08-10", time: "16:27:17"},
{id: 8, value : "value8", date: "2018-08-11", time: "10:27:17"}
];

arr.sort((a, b) => a.date.localeCompare(b.date) || a.time.localeCompare(b.time));
console.log(arr);

除非日期相同,否则将返回日期差。在这种情况下,localCompare将出现在0中,而时间差将被返回。

>

要排序为降序,只需切换ab

const arr = [{id: 1, value : "value1", date: "2018-08-08", time: "15:27:17"},
{id: 2, value : "value2", date: "2018-08-09", time: "12:27:17"},
{id: 3, value : "value3", date: "2018-08-10", time: "17:27:17"},
{id: 4, value : "value4", date: "2018-08-10", time: "01:27:17"},
{id: 5, value : "value5", date: "2018-08-10", time: "09:27:17"},
{id: 6, value : "value6", date: "2018-08-10", time: "23:27:17"},
{id: 7, value : "value7", date: "2018-08-10", time: "16:27:17"},
{id: 8, value : "value8", date: "2018-08-11", time: "10:27:17"}
];

arr.sort((a, b) => b.date.localeCompare(a.date) || b.time.localeCompare(a.time));
console.log(arr);