Chunk Array
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([1, 2, 3, 4, 5], 2);Output
[[1, 2], [3, 4], [5]]Explanation
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.
Hints
Chunk Array (reference solution)
One way to do it. The Editorial tab walks through why it is written this way.
Solution
1function chunk(arr, size) {
2 if (size <= 0) return [];
3 const out = [];
4 for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
5 return out;
6}Editorial: Chunk Array
Stepping by size
A loop that steps by size instead of by one, with slice doing the extraction.
Approach
The short final group needs no special case, because slice past the end simply stops at the end.
Implementation
function chunk(arr, size) { if (size <= 0) return []; const out = []; for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size)); return out; }
Worth knowing
The input worth thinking about is a size of zero or less. i += 0 never advances, so an unguarded loop hangs forever — the kind of thing that takes down a tab rather than throwing. Decide what it returns and guard before the loop.
slice copies, so the groups are independent of the input array.
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it