Split an Array Into Chunks

Arrays

Write chunk(arr, size) splitting the array into subarrays of length size.

The final group holds the remainder and may be shorter. A size of zero or less cannot produce groups — return an empty array.

Examples

Example 1
Input
chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3);
Output
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]
Explanation
Seven items in groups of three: two full groups, then one item left over.

Constraints

  • arr may be empty, and size may be larger than its length
  • size is an integer, and zero or a negative size returns []

Notes

  • `slice` past the end of an array simply stops, so the short final group needs no special case.

Hints

Read the full write-up for Split an Array Into Chunks
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it