Chunk an Array Into Batches
Split an array into fixed-size batches for bulk inserts, pagination, or parallel processing without mutating the original input.
Code
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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.RAG Document Chunk VisualizerSplit long documents into RAG chunks by character or word count with configurable overlap, boundary alignment, token stats, and highlighted overlaps.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.