Skip to content

Instantly share code, notes, and snippets.

@BalasubramaniM
Created August 19, 2021 01:00
Show Gist options
  • Save BalasubramaniM/3759801c85ca22b04d5b7e8bdf56b753 to your computer and use it in GitHub Desktop.
Save BalasubramaniM/3759801c85ca22b04d5b7e8bdf56b753 to your computer and use it in GitHub Desktop.
Chunk array by given size.
function chunk(arr, chunkSize) {
let result = [];
function getChunkedArr(arrToChunk) {
let res = [];
for(let i = 0; i < arrToChunk.length; i++) {
res.push(arrToChunk[i]);
}
return res;
}
for(let i = 0; i < arr.length;) {
const chunkedArr = arr.slice(i, i + chunkSize);
result.push(getChunkedArr(chunkedArr));
i += chunkSize;
}
return result;
};
console.log(chunk([1,2,3,4,5,6], 2)) // [[1,2], [3,4], [5,6]];
console.log(chunk([1,2,3,4,5], 2)) // [[1,2], [3,4], [5]];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment