Batching work by array slices gives the last batch permission to be shorter. Guard the requested size before using it as the loop increment.
Worked example
const chunk = (xs, n) =>
Array.from({ length: Math.ceil(xs.length / n) }, (_, i) =>
xs.slice(i * n, (i + 1) * n),
);
console.log(chunk([1, 2, 3, 4, 5], 2));Result
[ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]Implementation notes
Slicing copies the outer part of the array. Mutating an object inside a batch can still mutate the same object through the original collection.
Try it yourself
Test empty input, a partial last batch and an invalid size of zero.
Open the JavaScript example →Editorial date May 11, 2026 · Published December 6, 2026