Search code examples
javascriptarrayschunks

Chunk array in javascript by adding only 1 element from next chunk


I am looking to divide my array in JavaScript into chunk of 3. But I only want to increment the chunk by 1 element. Example below:

[1,2,3,4,5,6,7,8] => [1,2,3], [2,3,4], [3,4,5], [4,5,6], [5,6,7], [6,7,8]

All the resulted arrays should be of size 3. So only the one element is swiped to the left.

I have following code which divides the array into chunk of 3:

_.chunk($scope.substituteItems, 3);

This code divides the array as: [1,2,3,4,5,6,7,8] => [1,2,3], [3,4,5], [5,6,7], [8]

Obviously this code is only dividing the array into equal chunks which is not what I want.


Solution

  • You can use reduce() to loop through the array. Use slice() to shallow copy the array into chunks.

    let arr = [1, 2, 3, 4, 5, 6, 7, 8];
    let numOfChunk = 3;
    
    let result = arr.reduce((c, v, i, a) => {
      if (i + numOfChunk <= a.length) c.push(a.slice(i, i + numOfChunk));
      return c;
    }, [])
    
    
    console.log(result);


    You can also use concat() instead of push() if you prefer one line of code.

    let arr = [1, 2, 3, 4, 5, 6, 7, 8];
    let numOfChunk = 3;
    
    let result = arr.reduce((c, v, i, a) => i + numOfChunk <= a.length ? c.concat([a.slice(i, i + numOfChunk)]) : c, [])
    
    console.log(result);