Examples
Write chunk so that the following cases hold.
- Input
chunk([1,2,3,4,5], 2)Output[[1,2],[3,4],[5]] - Input
chunk([1,2,3], 3)Output[[1,2,3]] - Input
chunk([1,2,3], 5)Output[[1,2,3]]
1 more hidden test cases - 4 in total will be graded.
Answer
js
function chunk(arr, size) {
const out = [];
for (let i = 0; i < arr.length; i += size) {
out.push(arr.slice(i, i + size));
}
return out;
}
chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]
The last group may be shorter. A size larger than the array yields a single group; an empty array yields [].
