Chunk
Problem statement
Implement a function chunk(array, [size=1]) that splits the input array into groups of length size and returns them within a new array.
If the array cannot be split evenly, the final chunk will contain the remaining elements. The function should not modify the original input array.
Example
chunk(['a', 'b', 'c', 'd'], 2); // => [['a', 'b'], ['c', 'd']]
chunk([1, 2, 3, 4], 3); // => [[1, 2, 3], [4]]
How to approach Chunk
The strategy an interviewer expects you to reach for.
Chunking splits a list into fixed-size pages — think batching uploads or rendering windows. Naive move Nested loops that push one element at a time and forget the last partial chunk. Where it breaks Size < 1, non-arrays, and the remainder when length is not divisible by size. Mutating the source while slicing is unnecessary risk. The fix Guard bad input. Loop i += size and push(array.slice(i, i + size)). Slice naturally yields a shorter final chunk. Remember: slice(i, i+size) gives you the partial tail for free. Say this in the interview: I'd step by size and slice each window into a new array of chunks, including a shorter final page when needed.
The full solution is part of HelloFrontend Pro
The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.
- Runnable editor with the hidden test suite
- Progressive hints that unlock as you get stuck
- Senior-level reference solution with a line-by-line walkthrough
Already a member? Log in to open the workspace.