I have a problem with DateTime
in Javascript. My issue is that I have 2 array of DateTime
range. For example:
var list1 = [
{start: 2018-08-28 00:00:00, end: 2018-08-28 04:00:00},
{start: 2018-08-28 04:00:00, end: 2018-08-28 10:00:00},
{start: 2018-08-28 12:00:00, end: 2018-08-28 14:00:00},
{start: 2018-08-28 20:00:00, end: 2018-08-28 22:00:00},
];
var list2 = [
{start: 2018-08-28 03:00:00, end: 2018-08-28 06:00:00},
{start: 2018-08-28 11:00:00, end: 2018-08-28 11:30:00},
{start: 2018-08-28 13:00:00, end: 2018-08-28 17:00:00},
];
After merge two list the result will be:
result = [
{start: 2018-08-28 00:00:00, end: 2018-08-28 03:00:00},
{start: 2018-08-28 03:00:00, end: 2018-08-28 04:00:00},
{start: 2018-08-28 04:00:00, end: 2018-08-28 06:00:00},
{start: 2018-08-28 06:00:00, end: 2018-08-28 10:00:00},
{start: 2018-08-28 11:00:00, end: 2018-08-28 11:30:00},
{start: 2018-08-28 12:00:00, end: 2018-08-28 13:00:00},
{start: 2018-08-28 13:00:00, end: 2018-08-28 14:00:00},
{start: 2018-08-28 14:00:00, end: 2018-08-28 17:00:00},
{start: 2018-08-28 20:00:00, end: 2018-08-28 22:00:00},
];
This is a combination problem, not a sorting problem. For example: from 1:00 - 3:00 combine with 2:00 - 5:00 the result will be: [1:00 - 2:00, 2:00 - 3:00, 3:00 - 5:00].
If you have any idea please let me know.
Thank you in advance!
您可以使用Array.concat组合两个数组,然后使用自定义比较器对它们进行适当排序。
const output = list1.concat(list2).sort((a, b) => a.start - b.start);
It is now advisable to use ES6 syntax for joining the 2 arrays: Example below
result = [...list1, ...list2];
result.sort(function(a,b){
// Turn your strings into dates and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(b.start) - new Date(a.start);
});
The issue here is that you have a date , not a number or a string , that's why sorting will not work. You could make strings your dates:
var list1 = [ {start: "2018-08-28 00:00:00", end: "2018-08-28 04:00:00"}, {start: "2018-08-28 04:00:00", end: "2018-08-28 10:00:00"}, {start: "2018-08-28 12:00:00", end: "2018-08-28 14:00:00"}, {start: "2018-08-28 20:00:00", end: "2018-08-28 22:00:00"}, ]; var list2 = [ {start: "2018-08-28 03:00:00", end: "2018-08-28 06:00:00"}, {start: "2018-08-28 11:00:00", end: "2018-08-28 11:30:00"}, {start: "2018-08-28 13:00:00", end: "2018-08-28 17:00:00"}, ]; var result = list1.concat(list2).sort((a, b) => new Date(a.start) - new Date(b.start)); console.log(result)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.