Split array into chunks of size n
7 August 2022 (Updated 7 August 2022)
You want a function that takes an array and splits it into chunks of size n
. Something like this:
chunkArray([2, 4, 6, 8, 10, 12, 14], 2)
// [[2, 4], [6, 8], [10, 12], [14]
If the array cannot be chunked into exact chunks of n
, the remaining elements will form a separate chunk (e.g., [14]
in the above example).
Here’s how in JavaScript:
function chunkArray(arr, chunkSize) {
const chunkedArr = [];
for(let index = 0; index < arr.length; index += chunkSize) {
chunkedArr.push(arr.slice(index, index + chunkSize));
}
return chunkedArr;
}
Tagged:
Snippets