Open this example in the interactive library
Source code
const intervals = [
[1, 3],
[2, 5],
[8, 10],
];
const merged = [];
for (const [start, end] of intervals.toSorted((a, b) => a[0] - b[0])) {
const previous = merged.at(-1);
if (previous && start <= previous[1])
previous[1] = Math.max(previous[1], end);
else merged.push([start, end]);
}
console.log(merged);
Sample output
[ [ 1, 5 ], [ 8, 10 ] ]
