如何在数组上合并重叠的日期范围?
我有一系列日期:
const dates = [
{startDate: "2020-03-19T00:00:00+01:00", endDate: "2020-03-20T00:00:00+01:00"},
{startDate: "2020-03-09T00:00:00+01:00", endDate: "2020-03-16T00:00:00+01:00"},
{startDate: "2020-02-07T00:00:00+01:00", endDate: "2020-03-09T00:00:00+01:00"},
{startDate: "2020-02-07T00:00:00+01:00", endDate: "2020-02-13T00:00:00+01:00"}
];
我想要完成的是合并重叠的数组,这样我就会得到:
//Result I'm looking for:
const mergedDates = [
{startDate: "2020-03-19T00:00:00+01:00", endDate: "2020-03-20T00:00:00+01:00"},
{startDate: "2020-02-07T00:00:00+01:00", endDate: "2020-03-16T00:00:00+01:00"}
];
我正在使用moment-range
创建范围:
const ranges = dates.map(d => {
return moment.range(d.startDate, d.endDate);
});
然后我使用两个for
循环来找出重叠
let arrRange = [];
for (let i = 0; i < ranges.length; i++) {
const el1 = ranges[i];
let loop=[];
for (let i = 0; i < ranges.length; i++) {
const el2 = ranges[i];
const overlaps = el1.overlaps(el2, { adjacent: true });
if(overlaps){
loop = [...loop, i]
}
}
arrRange.push(loop);
}
}
这给了我一个数组,其中有索引数组,所以我知道重叠在哪里:
console.log(arrRange);
// [[0], [1, 2], [1, 2, 3], [2, 3]]
但是,我被困住了。
即使知道重叠,我也不知道如何合并它们。