Command Palette

Search for a command to run...

Hectal
Phase 3: Functions
JavaScript · Exercise 5 of 6 PreviousNext
Intermediate

Recursion through nested arrays

Write two recursive functions that work on arrays nested to any depth, like [1, [2, [3, [4]]], 5]:

sumNested(list) returns the sum of every number inside (an empty array gives 0).

flatten(list) returns a new flat array of every number in order, e.g. [1, 2, 3, 4, 5], without changing the array passed in.

What Check tests

  1. sumNested([1, [2, [3, [4]]], 5]) is 15
  2. Empty arrays, even nested ones, sum to 0
  3. It handles deep nesting
  4. flatten returns all numbers in order
  5. flatten doesn't change the array it was given

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

Runs in your browser. Your code is saved here.

Console

Nothing printed yet.