[Solved] Find all ranges of consecutive numbers in array [closed]


You can use Array.reduce() to do it:

  1. Sort the array (safety)
  2. Iterate over the array with reduce to create an object containing the ranges and the start of the active range (rangeStart).
  3. On the first iteration, push the first element in the ranges and save this element as the rangeStart
  4. 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 the ranges array and update rangeStart to be this element.
  5. Return the ranges property of the object output by reduce 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]