Split an array into groups (chunks) of a given size, e.g. chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],[5]].
Iterate in steps of size, slicing each window. slice safely handles the final partial chunk. Guard against size <= 0.
function chunk(arr, size) {
if (size <= 0) throw new Error('size must be > 0');
const out = [];
for (let i = 0; i < arr.length; i += size) {
out.push(arr.slice(i, i + size));
}
return out;
}Chunking batches API calls (send 100 records at a time) and paginates test data so you don't overload a service during load testing.
chunk(arr, 0) hangs the process. Why, and how do you prevent it?