How to chunk an array in JavaScript
12 May 2024 (Updated 12 May 2024)
function chunkArray<T>(array: Array<T>, chunkSize: number): Array<Array<T>> {
if (chunkSize <= 0) {
throw new Error("chunkSize must be greater than 0")
}
const chunkedArray: Array<Array<T>> = []
for (let index = 0; index < array.length; index += chunkSize) {
const chunk = array.slice(index, index + chunkSize);
chunkedArray.push(chunk)
}
return chunkedArray
}
const NUMS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(chunkArray(NUMS, 2))
console.log(chunkArray(NUMS, 3))
console.log(chunkArray(NUMS, 5)
Tagged:
JavaScript
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment