call(back)

Implement Lodash's chunk

Write chunk(array, size): split array into arrays of size elements; the last one may be shorter.

  • size is rounded down, and a size below 1 returns [].
  • Leave the input alone.
chunk([1, 2, 3, 4, 5], 2)   // [[1, 2], [3, 4], [5]]
chunk([1, 2, 3], 0)         // []

Hints

Hint 1

Step i by size and take slice(i, i + size).

Hint 2

Clamp the size first, because a size of 0 would loop forever — and Math.floor(NaN) is NaN, which fails every comparison.

Asked at