Arun Kumar
Arun Kumar

Reputation: 957

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.

Upvotes: 1

Views: 1157

Answers (2)

Eddie
Eddie

Reputation: 26844

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);

Upvotes: 2

chiliNUT
chiliNUT

Reputation: 19573

using native js... If your array of n elements is to be chunked into chunks of size c sequentially as you describe, there will be n-c+1 total chunks, in your case 8-3+1=6, map the first n-c+1 elements of the array to the chunk containing itself + the next 2:

let c=3, arr=[1,2,3,4,5,6,7,8];
let result=arr.slice(0,arr.length-c+1).map((v,k)=>arr.slice(k,k+c));
console.log(result); 

Upvotes: 2

Related Questions