Skip to the solution
MediumDSA5 min read

Implement _.chunk(array, size)

650 views

The problem

Problem, as an interviewer would state it: "Implement chunk(array, size) — splitting the array into groups of the given size, matching lodash's own well-known _.chunk behavior, including the real, correct handling of a remainder that does not evenly divide."

Examples:

Code
chunk([1,2,3,4,5,6], 2); // [[1,2],[3,4],[5,6]]
chunk([1,2,3,4,5], 2);   // [[1,2],[3,4],[5]] -- a smaller final chunk

Clarifying questions expected:

  • What is the real, correct behavior when the array length does NOT evenly divide by size — should the final chunk simply be smaller?
  • What should happen if size is larger than the entire array's own length?
  • What is the real, correct output for an invalid size, like 0 or a negative number?

Code / implementation expected: Yes — real, direct proof of even splitting, a genuine remainder correctly producing a smaller final chunk, a size larger than the whole array, and a genuinely invalid size.

  • chunk
  • array

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

5 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: chunk() correctly splits arrays of any size, including a real remainder case producing a correctly smaller final chunk via slice's own inherent bounds safety

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 107 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Implement memoize() with custom resolver and cache limit

Continue