You can use Array.reduce()
to do it:
- Sort the array (safety)
- Iterate over the array with
reduce
to create an object containing theranges
and the start of the active range (rangeStart
). - On the first iteration, push the first element in the ranges and save this element as the
rangeStart
- On the successive iterations, if the value equals the last value + 1, we are in the same range, so we update it by changing the last value in the
ranges
array. Otherwise, we push the element in theranges
array and updaterangeStart
to be this element. - Return the
ranges
property of the object output byreduce
and join it using commas.
function findRanges(numbers) {
return [...numbers].sort((a, b) => a - b).reduce((acc, x, i) => {
if (i === 0) {
acc.ranges.push(x);
acc.rangeStart = x;
} else {
if (x === acc.last + 1) {
acc.ranges[acc.ranges.length-1] = acc.rangeStart + '-' + x;
} else {
acc.ranges.push(x);
acc.rangeStart = x;
}
}
acc.last = x;
return acc;
}, { ranges: [] }).ranges.join(', ');
}
console.log(findRanges([1, 3, 4, 5, 7]));
console.log(findRanges([1, 2, 3, 5]));
console.log(findRanges([2, 3, 4, 5, 6]));
0
solved Find all ranges of consecutive numbers in array [closed]