Skip to content
GreenSnippets

Split an array into chunks

Break an array into fixed-size pieces, useful for batching API calls or database inserts.

JavaScript
function chunk(array, size) {
  if (!Number.isInteger(size) || size < 1) {
    throw new RangeError("size must be a positive integer");
  }
  const out = [];
  for (let i = 0; i < array.length; i += size) {
    out.push(array.slice(i, i + size));
  }
  return out;
}

Example / expected output

Output
chunk([1, 2, 3, 4, 5], 2) // [[1, 2], [3, 4], [5]]

How it works

Batching keeps request payloads and database statements within limits. The last chunk may be shorter. The size is validated so an accidental 0 cannot cause an infinite loop.