Lesson 5 of 8
Flattening nested lists
- 13 min
- 6 checks
- 3 hints
- Go to task
Goal
Turn a tree into a list
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.
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- There are six nodes in total
- Each node is followed by its children
- Every node has the right depth
- An empty list returns an empty list
- A node with no children doesn't cause an error
- The list is displayed in six rows