0

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

Like thisInput & output

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.

Jasper De Smet
  • 77
  • 1
  • 11

1 Answers1

0

To anyone that stumbles upon this question and is in the same situation here's a solution I came up with

var dates = [];
periods.forEach(x => {
  dates.push(x.startDate);
  dates.push(x.endDate);
})
dates = dates.sort((date1, date2) => date1 - date2);

newList = []
let lastDate;
for (var i = 0; i < dates.length; i++) {
  overlappingperiods = periods.filter(x => dates[i] >= x.startDate && dates[i] < x.endDate);
  if (i == dates.length - 2) {
    overlappingperiods.forEach(period => {
      newList.push({
        ...period,
        startDate: dates[i],
        endDate: dates[i + 1]
      })
    })
  } else {
    overlappingperiods.forEach(period => {
      newList.push({
        ...period,
        startDate: dates[i],
        endDate: dates[i + 1].addDays(-1)
      })
    })
  }
}

If anyone has found a better answer feel free to post it and i will mark it as the answer.

Jasper De Smet
  • 77
  • 1
  • 11