Split array into chunks of size n
7 August 2022 (Updated 27 October 2024)
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<T>(arr: T[], chunkSize: number) {
const chunkedArr = [];
for(let index = 0; index < arr.length; index += chunkSize) {
chunkedArr.push(arr.slice(index, index + chunkSize));
}
return chunkedArr;
}
Tagged:
Snippets
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment