#Arrays

Chunk Array

Split an array into groups of a fixed size, with whatever is left over in a shorter final group.

By Pratik RaiEasy

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

Input:

JSfile.javascript
1chunk([1, 2, 3, 4, 5], 2);

Output:

[[1, 2], [3, 4], [5]]

Two full groups and a remainder of one.

Constraints

  • 0 <= arr.length <= 10^5
  • Any integer size

Notes

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

Goal: Return groups of the requested size, with a short final group when needed.

Source

Frequently asked questions

How do you split an array into chunks?
Loop with a step equal to the chunk size and take a `slice` each iteration. The final slice returns whatever is left, so a short last group needs no special handling.
What should happen with a size of zero?
Nothing sensible can be produced, and an unguarded loop with `i += 0` never advances — it hangs the tab rather than throwing. Guard it and return an empty array.
Does chunking copy the data?
`slice` produces new arrays holding the same element references, so the groups are independent containers but the objects inside them are still shared with the input.
Where is chunking useful?
Paginating a list in memory, laying out a grid row by row, or splitting a large upload or API payload into batches the server will accept.

Related Challenges

Continue learning with these related challenges

View All
JavaScript

Array.prototype.map Polyfill

Implement Array.prototype.map from scratch. Master callback signatures, thisArg binding, and sparse-array hole preservation.

JavaScript · Arrays · PolyfillsPratik Rai ·

JavaScript

Array.prototype.filter Polyfill

Implement Array.prototype.filter from scratch. The key detail: push the original element, not the boolean result of the predicate.

JavaScript · Arrays · PolyfillsPratik Rai ·

JavaScript

Array.prototype.flat Polyfill

Implement Array.prototype.flat from scratch with a configurable depth. Default depth is 1, not Infinity.

JavaScript · Arrays · RecursionPratik Rai ·