How do I add consecutive numbers into separate arrays?

  • 0
    How to get a nested array of sequential numbers from the array of numbers
    [-1, 0, 1, 2, 3, 5, 7, 8, 9, 11, 14, 15, 17, 18, 20]
    only with built-in JS functions?
    To get it:
    [[-1, 0, 1, 2, 3], [5], [7, 8, 9], [11], [14, 15], [17, 18], [20]]
    JavaScript Colton Chambers, Sep 4, 2020

  • 1 Answers
  • 0
    arr.reduce((acc, n, i, a) => (
    n - 1 !== a[i - 1] && acc.push([]),
    acc[acc.length - 1].push(n),
    acc
    ), [])
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!