Skip to content
Advertisement

Group numbers from array that are right after each other

I have an array with some numbers like the following:

[1, 2, 3, 4, 6, 7, 8, 10, 15, 16, 17]

I’d like to show all numbers that are direct after each other (n+1) in one line and if there is a gap, this should be separated. This will either be done in javascript/jquery. The user would see it like this:

1 - 4, 6 - 8, 10, 15 - 17

I’m guessing the only solution to this would be to loop through the array and see if the next number is n+1 and if it is, lump it together, else start on a new series? I think I know how I would do it that way but interested to know if there is some other way to do it either in javascript/jquery?

Advertisement

Answer

You can loop once while keeping track of the current starting number.

let arr = [1, 2, 3, 4, 6, 7, 8, 10, 15, 16, 17];
let start = arr[0],
  res = [];
for (let i = 1; i < arr.length; i++) {
  if (arr[i + 1] - arr[i] != 1 || i == arr.length - 1) {
    res.push(start + " - " + arr[i]);
    start = arr[i + 1];
  }
}
console.log(res);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement