Chunk an array
Write chunk(arr, size) that splits arr into groups of size items. The last group holds whatever is left over.
chunk([1, 2, 3, 4], 2)→[[1, 2], [3, 4]]chunk([1, 2, 3, 4, 5], 2)→[[1, 2], [3, 4], [5]]chunk([1, 2, 3], 10)→[[1, 2, 3]]chunk([1, 2, 3], 0)→[]
Return [] for an empty array or when size is less than 1, and leave the input array untouched.
Define chunk in the editor. 7 tests will call it.
Hint 1Step through the array with an index that increases by size on every iteration.
Hint 2arr.slice(i, i + size) gives you one chunk without changing the input, and slice stops at the end of the array for you.
Hint 3Check for size less than 1 before the loop, otherwise the index never moves forward.
one clean solution
function chunk(arr, size) {
if (!(size >= 1)) return []; // also covers NaN and undefined
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}