Split an array into chunks

“Chunky”, a Green belt challenge from the CurlyScript Dojo. It uses what Grade 7: Arrays: Lists of Things teaches, and 3 tests check your answer.

The challenge

Write chunk(list, size) that splits an array into smaller arrays of size items. The last group can be smaller.

Example
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.

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
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.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning