Lesson 5 of 8

Flattening nested lists

Goal

Turn a tree into a list

01

Explanation

You'll run into nested lists everywhere, like comments that have replies and sections that have subsections, and what you need most often is to go through all of them as one flat list.

arr.flat(Infinity) is enough for nested arrays, but a real tree is made of objects with children, and those need recursion: the function calls itself on each branch.

Recursion always needs a base case where it stops, and here that's a node with no children.

02

Your task

Write flattenTree(nodes) to return a flat list in which every item stores its level in the tree as depth.

Checks

6 checks
  1. There are six nodes in total
  2. Each node is followed by its children
  3. Every node has the right depth
  4. An empty list returns an empty list
  5. A node with no children doesn't cause an error
  6. The list is displayed in six rows
03

Hints

0/3
Track lessons0 of 8 done

Write functions for searching, sorting, grouping and flattening nested lists once, then reuse them in every project after that.

Advanced level, 8 lessons, 1.5 hours in total.

index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.

Track lessons0 of 8 done

Write functions for searching, sorting, grouping and flattening nested lists once, then reuse them in every project after that.

Advanced level, 8 lessons, 1.5 hours in total.