Search code examples
javascriptlodash

Array splitting based on value


How could I split an array by value like this:

[0, 1, 2, 0, 0, 0, 1, 0] => [[0, 1, 2], [0], [0], [0, 1], [0]]?

I'm using lodash documentary, but kinda out of ideas for now. Is there any way to do this with _.groupBy? Thanks for your answers.


Solution

  • Use native JavaScrip Array#reduce method.

    var data = [0, 1, 2, 0, 0, 0, 1, 0],
      last;
    
    var res = data.reduce(function(arr, v) {
      // check the difference between last value and current 
      // value is 1
      if (v - last == 1)
        // if 1 then push the value into the last array element
        arr[arr.length - 1].push(v)
      else
        // else push it as a new array element
        arr.push([v]);
      // update the last element value
      last = v;
      // return the array refernece
      return arr;
      // set initial value as empty array
    }, [])
    
    console.log(res);