Chunk an Array Into Batches
Split an array into fixed-size batches for bulk inserts, pagination, or parallel processing without mutating the original input.
Code
export function chunk(items, size) {
if (!Number.isInteger(size) || size <= 0) {
throw new RangeError("size must be a positive integer");
}
const batches = [];
for (let i = 0; i < items.length; i += size) {
batches.push(items.slice(i, i + size));
}
return batches;
}Report a problem with this exampleOpens a pre-filled issue on GitHub.