Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Chunk an Array

Working With Arrayseasy

Course · Section 11: Working With Arrays · Lecture 149: Simple Array Methods

Implement `chunk(arr, size)` splitting `arr` into subarrays of length `size` (the last chunk may be shorter).

Sample tests

Input: chunk([1,2,3,4,5], 2)
Output: [[1,2],[3,4],[5]]
Input: chunk([1,2,3], 3)
Output: [[1,2,3]]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Mutating with splice instead of slicing.
  • An incorrect loop step duplicating or skipping elements.

Learning resources

  • MDN: Array
Approach & explanation (try first)

Looping with i += size and slicing each window groups the array into fixed-size chunks.

Loading...
⌘/Ctrl + Enter

Run your code to see results.