0

I hope that, I'm explaining myself right. I need to write a function that gets an array of numbers and returns an array of ranges if there is.

For example:

[1,2,3,5,6,8,9,10] -----> [[1,2,3],[5,6],[8,9,10]]

Kamuran Sönecek
  • 3,293
  • 2
  • 30
  • 57
  • Show what you have tried so far, explain how it fails and we might be able to help. – connexo Oct 23 '19 at 12:01
  • It's not clear how the function will return ranges – Pratik Oct 23 '19 at 12:01
  • is the data ordered, as it looks like? – Nina Scholz Oct 23 '19 at 12:01
  • hey Michal, there is no such built-in function. Please show us if you tried anything and we can help you from there. – Gibor Oct 23 '19 at 12:02
  • What's the correlation between your input and expected output? – Andy Oct 23 '19 at 12:02
  • _“I hope that I'm explaining myself right.”_ - by _just_ explaining what you “need”, you are not even _asking_ right to begin with. This site is not a research service or a code-writing service; we want you to show us what you already tried to solve the problem yourself first of all. Please go read [ask]. – 04FS Oct 23 '19 at 12:15
  • thank you for trying to help me!! but i got my answer – Michal Avraham Oct 23 '19 at 12:16

1 Answers1

1

You could check the previous value and insert a new array, if the delta is not one.

var array = [1, 2, 3, 5, 6, 8, 9, 10],
    result = array.reduce((r, v, i, { [i - 1]: p }) => {
        if (p === v - 1) r[r.length - 1].push(v);
        else r.push([v]);
        return r;
    }, []);

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392