Search code examples
javascriptsplitsequential

Split array into chunks of array if it is sequential in javaScript


I want to spilt array in chunks of array Input= [36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,57,58,59,60,61,62] Output= {[36,37,38,39],[40,41,42,43],[44,45,46,47],[48,49,50,51],[57,58,59,60]}

If there are no sequential numbers from 52 so it should not take that.
Can anyone help me out?
Thanks in advance.

I am currently using this code but in output it is not checking the sequence

    ```Array.prototype.chunk = function(n) {
      if (!this.length) {
        return [];
      }
      return [this.slice(0, n)].concat(this.slice(n).chunk(n));
    };
    console.log([36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72].chunk(4));    ```
This output is what i am currently getting but i want output as i mentioned above.
Output:

[
  [ 36, 37, 38, 39 ],
  [ 40, 41, 42, 43 ],
  [ 44, 45, 46, 47 ],
  [ 48, 49, 50, 51 ],
  [ 52, 57, 58, 59 ],
  [ 60, 61, 62, 63 ],
  [ 64, 65, 66, 67 ],
  [ 68, 69, 70, 71 ],
  [ 72 ]
]
      

Solution

  • Not sure this is what you expected but you will get expected output in this way

    console.log(chunk([36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72], 4));
    
    function checkSequence(arr) {
      for (let i = 1; i < arr.length; i++) {
        if (arr[i] - arr[i - 1] > 1) {
          return false;
        }
      }
      return true;
    }
    function chunk(arr, n) {
      let i = 0;
      var arr1 = [];
      while (i < arr.length) {
        const res = arr.slice(i, i + n);
        if (checkSequence(res) && res.length === 4) {
          arr1.push(res);
          i = i + n;
        } else {
          i = i + 1;
        }
      }
      return arr1;
    }