← JavaScript Coding

Chunk

easy

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.

Premium

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
Unlock the full solution →

Already a member? Log in to open the workspace.

More JS Coding questions

View all JS Coding →
JS CodingMedium

5. Throttle

JS CodingMedium

13. Deep Clone

JS CodingMedium

14. Event Emitter

JS CodingEasy

66. Promise Methods

JS CodingEasy

19. Memoize I

JS CodingMedium

86. API Retry

Explore related prep hubs

  • All JavaScript coding
  • JavaScript interview questions
  • JS polyfill interview questions
  • Debounce & throttle questions
  • React interview hub