1

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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

Also the code has to be compatible with IE. IE doesn't support let command.
just use var instead of let and it should work exactly the same

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.