I have an array of objects with a start date and an end date.
Example:
var periods = [
{
id: "Period1",
startDate: new Date("2022-08-29"),
endDate: new Date("2022-12-23")
},
{
id: "Period2",
startDate: new Date("2022-12-12"),
endDate: new Date("2023-10-02")
},
...
]
I need to split these periods when they overlap into a new object
This is what I tried so far in javascript
Date.prototype.addDays = function (days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
var periods = [
{
id: "Period1",
startDate: new Date("2022-08-29"),
endDate: new Date("2022-12-23")
},
{
id: "Period2",
startDate: new Date("2022-12-12"),
endDate: new Date("2023-10-02")
},
]
var dates = [];
periods.forEach(x => {
dates.push(x.startDate);
})
dates = dates.sort((date1, date2) => date1 - date2);
dates.forEach(date => {
overlappingperiods = periods.filter(x => date >= x.startDate && date <= x.endDate);
if (overlappingperiods.length > 1) {
overlappingperiods.forEach(period => {
periods.push({
...period,
id: period.id,
endDate: date.addDays(-1),
})
period.startDate = date;
})
}
})
console.log(periods);
Expected:
//Period1
//29/08/2022 - 11/12/2022
//12/12/2022 - 23/12/2022
//Period2
//12/12/2022 - 23/12/2022
//24/12/2022 - 10/02/2023
This works when the overlap happens on the start date (Period 1) but I can't wrap my head around what should happen when a period ends.
Any and all help is appreciated.