Split an array into chunks
Break an array into fixed-size pieces, useful for batching API calls or database inserts.
- JavaScript
- GreenSnippets
- MIT
- Executed with Node.js 22
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
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.
Related snippets
- JavaScript Tested
Remove duplicates from an array
Deduplicate primitives with a Set, or objects by a key or computed value, keeping the first occurrence.
- JavaScript Tested
Sort an array by multiple keys
Sort objects by one field, then break ties with another, with ascending or descending order per field.
- TypeScript Tested
Non-empty array type
Encode "at least one element" in the type so head, max and similar functions never see an empty array.
- PHP Tested
Group an array of records by a key
Turn a flat list of associative arrays into groups keyed by a field or callback.

