Javascript - 按日期然后按时间对对象数组进行排序
Posted
技术标签:
【中文标题】Javascript - 按日期然后按时间对对象数组进行排序【英文标题】:Javascript - Sort array of objects by date then by time 【发布时间】:2019-01-16 09:16:17 【问题描述】:我有以下数组:
[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 结构,我如何对数组进行排序以同时考虑这两个字段(date
和 time
)?
【问题讨论】:
How to sort date strings (format exmaple: 2014 7 23) in javascript?的可能重复 你好,答案似乎没有考虑与日期分开的第二个属性时间。 【参考方案1】:按date
s 中的差异排序,如果没有差异,则在单个.sort
函数中按time
s 中的差异排序:
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
,并且将返回时间差异。
要改为降序排序,只需切换a
s 和b
s:
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);
【讨论】:
这个是升序排列的,如何在升序和降序之间交替?以上是关于Javascript - 按日期然后按时间对对象数组进行排序的主要内容,如果未能解决你的问题,请参考以下文章