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

Viewed 16131

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]

13 Answers

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"]

Just having fun with solution from CMS :

  function getRanges (array) {
    for (var ranges = [], rend, i = 0; i < array.length;) {
      ranges.push ((rend = array[i]) + ((function (rstart) {
        while (++rend === array[++i]);
        return --rend === rstart;
      })(rend) ? '' : '-' + rend)); 
    }
    return ranges;
  }

I needed TypeScript code today to solve this very problem -- many years after the OP -- and decided to try a version written in a style more functional than the other answers here. Of course, only the parameter and return type annotations distinguish this code from standard ES6 JavaScript.

  function toRanges(values: number[],
                    separator = '\u2013'): string[] {
    return values
      .slice()
      .sort((p, q) => p - q)
      .reduce((acc, cur, idx, src) => {
          if ((idx > 0) && ((cur - src[idx - 1]) === 1))
            acc[acc.length - 1][1] = cur;
          else acc.push([cur]);
          return acc;
        }, [])
      .map(range => range.join(separator));
  }

Note that slice is necessary because sort sorts in place and we can't change the original array.

Here's my take on this...

function getRanges(input) {

  //setup the return value
  var ret = [], ary, first, last;

  //copy and sort
  var ary = input.concat([]);
  ary.sort(function(a,b){
    return Number(a) - Number(b);
  });

  //iterate through the array
  for (var i=0; i<ary.length; i++) {
    //set the first and last value, to the current iteration
    first = last = ary[i];

    //while within the range, increment
    while (ary[i+1] == last+1) {
      last++;
      i++;
    }

    //push the current set into the return value
    ret.push(first == last ? first : first + "-" + last);
  }

  //return the response array.
  return ret;
}

Rough outline of the process is as follows:

  • Create an empty array called ranges
  • For each value in sorted input array
    • If ranges is empty then insert the item {min: value, max: value}
    • Else if max of last item in ranges and the current value are consecutive then set max of last item in ranges = value
    • Else insert the item {min: value, max: value}
  • Format the ranges array as desired e.g. by combining min and max if same

The following code uses Array.reduce and simplifies the logic by combining step 2.1 and 2.3.

function arrayToRange(array) {
  return array
    .slice()
    .sort(function(a, b) {
      return a - b;
    })
    .reduce(function(ranges, value) {
      var lastIndex = ranges.length - 1;
      if (lastIndex === -1 || ranges[lastIndex].max !== value - 1) {
        ranges.push({ min: value, max: value });
      } else {
        ranges[lastIndex].max = value;
      }
      return ranges;
    }, [])
    .map(function(range) {
      return range.min !== range.max ? range.min + "-" + range.max : range.min.toString();
    });
}
console.log(arrayToRange([2, 3, 4, 5, 10, 18, 19, 20]));

If you simply want a string that represents a range, then you'd find the mid-point of your sequence, and that becomes your middle value (10 in your example). You'd then grab the first item in the sequence, and the item that immediately preceded your mid-point, and build your first-sequence representation. You'd follow the same procedure to get your last item, and the item that immediately follows your mid-point, and build your last-sequence representation.

// Provide initial sequence
var sequence = [1,2,3,4,5,6,7,8,9,10];
// Find midpoint
var midpoint = Math.ceil(sequence.length/2);
// Build first sequence from midpoint
var firstSequence = sequence[0] + "-" + sequence[midpoint-2];
// Build second sequence from midpoint
var lastSequence  = sequence[midpoint] + "-" + sequence[sequence.length-1];
// Place all new in array
var newArray = [firstSequence,midpoint,lastSequence];

alert(newArray.join(",")); // 1-4,5,6-10

Demo Online: http://jsbin.com/uvahi/edit

 ; For all cells of the array
    ;if current cell = prev cell + 1 -> range continues
    ;if current cell != prev cell + 1 -> range ended

int[] x  = [2,3,4,5,10,18,19,20]
string output = '['+x[0]
bool range = false; --current range
for (int i = 1; i > x[].length; i++) {
  if (x[i+1] = [x]+1) {
    range = true;
  } else { //not sequential
  if range = true
     output = output || '-' 
  else
     output = output || ','
  output.append(x[i]','||x[i+1])
  range = false;
  } 

}

Something like that.

Here's a version in Coffeescript

getRanges = (array) -> 
    ranges = []
    rstart
    rend
    i = 0
    while  i < array.length
      rstart = array[i]
      rend = rstart
      while array[i + 1] - array[i] is 1
        rend = array[i + 1] # increment the index if the numbers sequential
        i = i  + 1
      if rstart == rend 
        ranges.push  rstart + ''
      else
        ranges.push rstart + '-' + rend
      i = i + 1
    return ranges
Related