Created
August 19, 2021 01:00
-
-
Save BalasubramaniM/3759801c85ca22b04d5b7e8bdf56b753 to your computer and use it in GitHub Desktop.
Chunk array by given size.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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