Chunk an array

Chunking splits an array into consecutive sub-arrays of a given size (the last one may be shorter); loop in steps of size and slice(i, i + size), which is O(n) and does not mutate the original.

Implementation choices

  • for loop with slice: clear and fast.
  • Array.from({ length: Math.ceil(n / size) }, (_, i) => arr.slice(i * size, i * size + size)): concise one-liner.
  • Generator: yields chunks lazily, perfect for huge or streamed data.
  • reduce: possible but harder to read.

Validation

size must be a positive integer. Decide how to handle 0, negatives and non-integers (throw a RangeError, as below). An empty input returns [].

Where chunking is used

  • Batching API calls (send 100 records per request, or process at most N in parallel).
  • Pagination on the client.
  • Grid layouts (rows of N cards).
  • Rate-limited processing combined with delays between batches.

Related operations

  • Sliding windows (overlapping chunks, e.g. moving averages): advance by 1 instead of by size.
  • Split by a condition (start a new chunk when a value changes): use a loop that compares with the previous item.

Code example

js
1function chunk(arr, size) {
2 if (!Number.isInteger(size) || size < 1) throw new RangeError("size must be a positive integer");
3 const out = [];
4 for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
5 return out;
6}
7
8const chunkOneLiner = (arr, size) =>
9 Array.from({ length: Math.ceil(arr.length / size) }, (_, i) => arr.slice(i * size, i * size + size));
10
11function* chunkLazy(iterable, size) {
12 let batch = [];
13 for (const item of iterable) {
14 batch.push(item);
15 if (batch.length === size) {
16 yield batch;
17 batch = [];
18 }
19 }
20 if (batch.length) yield batch;
21}
22
23const nums = [1, 2, 3, 4, 5, 6, 7];
24console.log(chunk(nums, 3)); // [[1, 2, 3], [4, 5, 6], [7]]
25console.log(chunkOneLiner(nums, 2)); // [[1, 2], [3, 4], [5, 6], [7]]
26console.log([...chunkLazy(new Set("abcde"), 2)]); // [["a", "b"], ["c", "d"], ["e"]]
27console.log(chunk([], 4)); // []
28
29// Batching requests: at most 2 at a time
30const ids = [101, 102, 103, 104, 105];
31const fetchUser = (id) => new Promise((r) => setTimeout(() => r({ id }), 5));
32const results = [];
33for (const batch of chunk(ids, 2)) results.push(...(await Promise.all(batch.map(fetchUser))));
34console.log(results.map((u) => u.id)); // [101, 102, 103, 104, 105]
35
36// Sliding window (overlapping)
37const windows = (arr, size) => arr.slice(0, arr.length - size + 1).map((_, i) => arr.slice(i, i + size));
38console.log(windows([1, 2, 3, 4], 2)); // [[1, 2], [2, 3], [3, 4]]

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app