The challenge
Write chunk(list, size) that splits an array into smaller arrays of size items. The last group can be smaller.
chunk([1, 2, 3, 4, 5], 2) // [[1, 2], [3, 4], [5]]
Try it
Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.
It prints
What the tests check
chunk([1, 2, 3, 4, 5], 2)gives[[1, 2], [3, 4], [5]]chunk(["a", "b", "c"], 3)gives[["a", "b", "c"]]chunk([], 4)gives[]
Hints
Stuck? Open one hint at a time. Try again after each one.
Hint 1
Loop with i += size, and use list.slice(i, i + size) for each group.
A solution
There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.
Show one possible solution
function chunk(list, size) {
const groups = [];
for (let i = 0; i < list.length; i += size) {
groups.push(list.slice(i, i + size));
}
return groups;
}
Learn what you need
This exercise uses what Grade 7: Arrays: Lists of Things teaches. Read those notes first if any of it is new.