How to reduce consecutive integers in an array to hyphenated range expressions?

gokul picture gokul · Feb 16, 2010 · Viewed 14k times · Source

In JavaScript, how can I convert a sequence of numbers in an array to a range of numbers? In other words, I want to express consecutive occurring integers (no gaps) as hyphenated ranges.

[2,3,4,5,10,18,19,20] would become [2-5,10,18-20]

[1,6,7,9,10,12] would become [1,6-7,9-10,12]

[3,5,99] would remain [3,5,99]

[5,6,7,8,9,10,11] would become [5-11]

Answer

Christian C. Salvadó picture Christian C. Salvadó · Feb 16, 2010

Here is an algorithm that I made some time ago, originally written for C#, now I ported it to JavaScript:

function getRanges(array) {
  var ranges = [], rstart, rend;
  for (var i = 0; i < array.length; i++) {
    rstart = array[i];
    rend = rstart;
    while (array[i + 1] - array[i] == 1) {
      rend = array[i + 1]; // increment the index if the numbers sequential
      i++;
    }
    ranges.push(rstart == rend ? rstart+'' : rstart + '-' + rend);
  }
  return ranges;
}

getRanges([2,3,4,5,10,18,19,20]);
// returns ["2-5", "10", "18-20"]
getRanges([1,2,3,5,7,9,10,11,12,14 ]);
// returns ["1-3", "5", "7", "9-12", "14"]
getRanges([1,2,3,4,5,6,7,8,9,10])
// returns ["1-10"]