Skip to content

Instantly share code, notes, and snippets.

@agiron123
Created August 22, 2019 22:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agiron123/81ec51efba3cf001a860303a701d6376 to your computer and use it in GitHub Desktop.
Save agiron123/81ec51efba3cf001a860303a701d6376 to your computer and use it in GitHub Desktop.
// https://stackoverflow.com/questions/8495687/split-array-into-chunks/10456644#10456644
let perChunk = 3; // items per chunk
let inputArray = [1,2,3,4,5,6,7,8,9];
const result = inputArray.reduce((resultArray, item, index) => {
const chunkIndex = Math.floor(index / perChunk);
if (!resultArray[chunkIndex]) {
resultArray[chunkIndex] = []; // start a new chunk
}
resultArray[chunkIndex].push(item);
return resultArray;
}, []);
console.log("Chunked Array: ", result);
return result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment