Is there a way to efficiently remove any overlaps between the start and end times (moment.js) in a given array of objects?
[{ start: moment("2019-03-23T15:55:00.000"), end: moment("2019-03-23T16:55:00.000")},
{ start: moment("2019-03-23T14:40:00.000"), end: moment("2019-03-23T17:30:00.000")},
{ start: moment("2019-03-23T18:45:00.000"), end: moment("2019-03-23T19:45:00.000")},
{ start: moment("2019-03-23T17:10:00.000"), end: moment("2019-03-23T20:00:00.000")},
{ start: moment("2019-03-23T21:35:00.000"), end: moment("2019-03-23T22:35:00.000")},
{ start: moment("2019-03-23T19:15:00.000"), end: moment("2019-03-23T22:05:00.000")},
{ start: moment("2019-03-23T22:30:00.000"), end: moment("2019-03-23T23:30:00.000"),
}]
In the scenario above, all dates fall on the same day (03/23). To achieve the desired result, the algorithm should identify the earliest start time and the latest end time without any overlaps among the objects. The final array should consist of alternating start, end, start, end ...
times.
For the provided example, the filtered result should be as follows:
start: 14:40:00
end: 17:30:00
start: 18:45:00
end: 20:00:00
start: 21:35:00
end: 23:30:00
In this output, start times are arranged chronologically, ensuring no overlaps between start and end times. All subsequent start times must occur after the previous end time.
Despite attempts to address overlapping issues, the current solution is ineffective. It still allows overlaps, highlighting the need for a more robust approach.
times.forEach(time => {
// start with the first object
if (filtered.length === 0) {
filtered.push({'start': time.start, 'end': time.end});
}
// if this start time is AFTER the prior end time, add it
if (time.start.isAfter(filtered[filtered.length-1]['end'])) {
filtered.push({'start': time.start, 'end': time.end});
}
if (time.start.isBefore(filtered[filtered.length-1]['end'])) {
// replace the prior end time
filtered[filtered.length-1]['end'] = time.end;
}
});
It is evident that the existing solution does not efficiently eliminate overlaps. Further exploration is needed to devise a more effective strategy.