How can I merge overlapping date ranges, on an array?
I have an array of dates:
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"}
];
What I'm looking to accomplish is to have the overlapping arrays merged so I would have as result:
//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"}
];
I'm using the moment-range
to create the ranges:
const ranges = dates.map(d => {
return moment.range(d.startDate, d.endDate);
});
Then I'm using two for
loops to find out the overlapping
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);
}
}
This gives me an array where I have arrays of indexes, so I know where are the overlaps:
console.log(arrRange);
// [[0], [1, 2], [1, 2, 3], [2, 3]]
However, I'm stuck.
Even knowing the overlaps, I can't figure out how to merge them.