Chunk an Array Into Batches

Split an array into fixed-size batches for bulk inserts, pagination, or parallel processing without mutating the original input.

JavascriptData Integrity

Code

javascriptsnippet
10 lines
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;
}

How the snippet works

Chunk an Array Into Batches is built around the function chunk.

Iteration happens inside for (let i = 0; i < items.length; i += size) — everything outside it runs once. RangeError is the guard’s signal — thrown at the branch, before any partial work happens.

Applying it

The primary signature is export function chunk(items, size)

Treat chunk as the API: import it, and ignore the supporting code.

Statements that matter

throw new RangeError("size must be a positive integer");
for (let i = 0; i < items.length; i += size) {
batches.push(items.slice(i, i + size));
}

Interactive Tools for This Topic

FAQ

How does the code behave when input is bad?
Validation comes first — `RangeError` marks the failure, before any partial work happens.
Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. The file defines `chunk` at load time.