Split an array into chunks in JavaScript
Beginner · 3 min read
Splitting a list into groups of a fixed size is called chunking. You use it to show products three to a row, to send records to a server 100 at a time, or to split a long list into pages. With seven items in groups of three, you get two full groups and one group holding the last item.
In this tutorial you will write chunk(values, size), which turns [1, 2, 3, 4, 5, 6, 7] into [[1, 2, 3], [4, 5, 6], [7]]. You need to know what an array, a for loop and a function are.
The tool: slice
slice(start, end) copies part of an array. It starts at position start and stops just before end. It never changes the original array.
const nums = [1, 2, 3, 4, 5, 6, 7];
console.log(nums.slice(0, 3)); // [ 1, 2, 3 ]
console.log(nums.slice(3, 6)); // [ 4, 5, 6 ]
console.log(nums.slice(6, 9)); // [ 7 ]
console.log(nums); // [ 1, 2, 3, 4, 5, 6, 7 ]
Look at the last slice. The array has no position 8, but slice doesn't mind. It stops at the end and hands back what is there. That is exactly the "last group holds whatever is left" rule, for free.
The pattern is clear too: the starts go 0, 3, 6, which is "count up by the group size".
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
44 Chunk an array into fixed-size pieces
easySplit a list into groups of a given size, with the last group holding whatever is left over.
Stuck? Three hints, smallest first
- 1.
slice(i, i + size)in a loop stepping bysizeis the whole job. - 2. A size of zero or less would loop forever. Refuse it.
- 3.
Array.from({ length: Math.ceil(n / size) })gives a version with no mutation.
Step 1: loop in steps of size
A for loop doesn't have to count up by one. Write i += size and it jumps ahead a whole group each time:
function chunk(values, size) {
const out = [];
for (let i = 0; i < values.length; i += size) out.push(values.slice(i, i + size));
return out;
}
console.log(chunk([1, 2, 3, 4, 5, 6, 7], 3)); // [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7 ] ]
console.log(chunk([1, 2, 3, 4], 2)); // [ [ 1, 2 ], [ 3, 4 ] ]
console.log(chunk([1, 2], 9)); // [ [ 1, 2 ] ]
console.log(chunk([], 3)); // []
Each time round, slice(i, i + size) copies one group and push adds it to the result. A size bigger than the list gives one group, and an empty list gives no groups, because the loop never runs.
Step 2: think about a size of zero
What does chunk([1, 2], 0) do? The loop adds 0 to i each time, so i stays at 0 forever. The condition i < values.length is always true, and the loop never ends. The page freezes, and no error appears to tell you why.
A negative size is no better, and a size like 1.5 makes no sense for "groups of". So the function should refuse anything that isn't a whole number of 1 or more. Number.isInteger(size) is true only for whole numbers.
Step 3: refuse a bad size
Throwing an error stops the function with a clear message. RangeError is the built-in error type for "this value is outside the allowed range":
function chunk(values, size) {
if (!Number.isInteger(size) || size < 1) {
throw new RangeError(`chunk size must be a whole number of 1 or more, got ${size}`);
}
const out = [];
for (let i = 0; i < values.length; i += size) out.push(values.slice(i, i + size));
return out;
}
try {
chunk([1, 2], 0);
} catch (err) {
console.log(err.message); // chunk size must be a whole number of 1 or more, got 0
}
try runs the code, and if it throws, catch receives the error so you can read its message. An infinite loop has become an error you can see and fix.
Step 4: a version without push
You can also work out the number of groups up front. Seven items in groups of three need Math.ceil(7 / 3), which is 3 groups (Math.ceil rounds up). Array.from({ length: n }, fn) builds an array of n items by calling fn with each index:
const chunkFrom = (values, size) =>
Array.from({ length: Math.ceil(values.length / size) }, (_, i) =>
values.slice(i * size, i * size + size));
console.log(chunkFrom([1, 2, 3, 4, 5], 2)); // [ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]
The _ is a name for the first argument, which this code doesn't use. Group i starts at i * size. This version has no guard, so use it only once the size has been checked.
The full solution
The answer panel has the guarded chunk and the Array.from version. It chunks two lists and shows the message for a size of zero. The checks also confirm the original array is never changed. Press Run to see the output.
function chunk(values, size) {
if (!Number.isInteger(size) || size < 1) {
throw new RangeError(`chunk size must be a whole number of 1 or more, got ${size}`);
}
const out = [];
for (let i = 0; i < values.length; i += size) out.push(values.slice(i, i + size));
return out;
}
// The same without a mutable accumulator.
const chunkFrom = (values, size) =>
Array.from({ length: Math.ceil(values.length / size) }, (_, i) =>
values.slice(i * size, i * size + size));
console.log(chunk([1, 2, 3, 4, 5, 6, 7], 3));
console.log(chunk(['a', 'b', 'c'], 1));
let refused = '';
try { chunk([1, 2], 0); } catch (err) { refused = err.message; }
console.log('refused:', refused);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('an uneven split keeps the remainder', chunk([1, 2, 3, 4, 5, 6, 7], 3), [[1, 2, 3], [4, 5, 6], [7]]);
test('an exact split', chunk([1, 2, 3, 4], 2), [[1, 2], [3, 4]]);
test('size one wraps each item', chunk(['a', 'b'], 1), [['a'], ['b']]);
test('a size larger than the list gives one chunk', chunk([1, 2], 9), [[1, 2]]);
test('an empty list gives no chunks', chunk([], 3), []);
test('size zero is refused', refused.includes('1 or more'), true);
test('both versions agree', chunkFrom([1, 2, 3, 4, 5], 2), chunk([1, 2, 3, 4, 5], 2));
test('the original is not modified', (() => { const a = [1, 2, 3]; chunk(a, 2); return a; })(), [1, 2, 3]);
The guard is not padding. With size of zero, i += 0 never advances and the loop runs until the tab dies — a hang rather than an error, which is much harder to diagnose. Refusing it up front turns an infinite loop into a clear message.
Common mistakes
- No guard on the size. A size of 0 hangs the page instead of throwing, which is much harder to track down.
- Using
spliceinstead ofslice.spliceremoves items from the original array, so the caller's list is emptied as you chunk it. - Dropping the last group. Looping only while
i + size <= values.lengthskips the leftover items. Letslicehand back the short last group.
Try it yourself
- Use
chunkto split 10 names into pages of 4, then print "Page 1", "Page 2" and "Page 3" with the names on each. - Write
unchunk(groups)that turns the groups back into one flat list. (Hint: look upflat.) - Make a version that pads the last group with
nullso every group has the same length.