Build a tree from a flat parent list
Comment threads, category menus and file trees all come out of a database flat: each row carries its own id and its parent's id. The UI needs them nested.
Implement buildTree(rows). Each row is an object with an id and a parentId, and may carry any other fields. Return an array of root nodes. Each node is a new object holding a copy of its row's own properties plus a children array of its child nodes, which is empty for a leaf. Children appear in the order their rows appear in the input, and so do the roots. A row is a root when its parentId is null, or when no row in the input has that id — an orphan is promoted to a root rather than dropped. Rows may appear in any order, so a child may come before its parent. The input rows must not be modified: no children property is ever added to them. An empty input returns an empty array.
What it has to do
- Return an array of root nodes, each a new object with the row's fields plus
children. - Give every node a
childrenarray, empty when it has no children. - Order children and roots by the order their rows appear in the input.
- Treat a row whose
parentIdisnullor refers to no known id as a root. - Accept rows in any order, and never add
childrento the input rows.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.