Flat list to a tree
A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.
The task
Each item looks like `{ id, parentId, name }`, where `parentId` is the `id` of another item, or `null` for a top-level item. Return the top-level items as an array of nodes `{ id, name, children }`, where `children` holds the node's child nodes in the same shape (an empty array when there are none). Nodes keep the order of the input list, at every level. A child can appear in the list before its parent. Every `parentId` that is not `null` refers to an item in the list. Do not change the items.
What this exercise teaches
Creating all the nodes before linking any of them is what makes the order of the list irrelevant: by the second pass every parent already exists in the Map. Doing both in one pass only works when parents happen to come first.
A hint if you get stuck
Make two passes. First create a node for every item and store it in a `Map` by id. Then go through the items again and push each node into its parent's `children`, or into the result when `parentId` is `null`.
Try it now, free, no account needed
Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.
Open this exerciseMore exercises in Data shaping
- CSV text to objectsFree
- Totals per customerFree
- Pivot rows into a lookupFree
- Top N with tiesFree
- Running totalsFree
- Read a nested value by pathFree
- Deep equalityFree
- Flatten a nested objectFree
- Left join two listsFree
- Merge overlapping intervalsFree
- Most frequent valuesFree
- Deep cloneFree
- Unflatten dotted keysFree
- All orderings of a listFree