Flatten a nested array

“Flatten it”, a Black belt challenge from the CurlyScript Dojo. It uses what Grade 10: Array Power Tools: map, filter & reduce teaches, and 3 tests check your answer.

The challenge

Write flatten(list) that takes an array that may contain arrays (nested to any depth) and returns one flat array. Try to write it yourself, without the built-in .flat()!

Example
flatten([1, [2, [3, [4]], 5]])  // [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

  • flatten([1, [2, [3, [4]], 5]]) gives [1, 2, 3, 4, 5]
  • flatten([[["a"]], "b"]) gives ["a", "b"]
  • flatten([]) gives []

Hints

Stuck? Open one hint at a time. Try again after each one.

Hint 1

Array.isArray(x) tells you if something is an array.

Hint 2

A function can call itself! If an item is an array, flatten that item too and add all of its results. This is called recursion.

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 flatten(list) {
  const result = [];
  for (const item of list) {
    if (Array.isArray(item)) result.push(...flatten(item));
    else result.push(item);
  }
  return result;
}

Learn what you need

This exercise uses what Grade 10: Array Power Tools: map, filter & reduce 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