Dev Helpers

JavaScript / Arrays

Chunk an array

Dev Helpers · May 11, 2026

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

Related articles

Flatten nested arrays

Choose the flattening depth from the data contract. Flattening another level can erase a meaningful grouping.

Remove duplicate values

Set preserves insertion order and collapses repeated primitive values. Objects still compare by reference.

Sum distances with a Euclidean norm

A diagonal is longer than either of its components. Math.hypot combines perpendicular distances without making the caller square each input.