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.
Arguments
rowsArray<{ id, parentId, ...rest }>- The flat records. Each carries its own id and the id of its parent (
nullfor a root).
Returns
Array<{ ...rest, children: Array }> — The roots of the forest, each a new node with the row's fields plus a children array (empty for a leaf).
Examples
buildTree([
{ id: 1, parentId: null },
{ id: 2, parentId: 1 },
{ id: 3, parentId: 1 },
]);
// [{ id: 1, parentId: null, children: [
// { id: 2, parentId: 1, children: [] },
// { id: 3, parentId: 1, children: [] },
// ] }]buildTree([
{ id: 1, parentId: null },
{ id: 9, parentId: 404 },
]).map((node) => node.id);
// [1, 9] — an orphan (parentId not in the list) is promoted to a rootWhat 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.
Stuck? The javascript course covers everything this challenge needs.
- 1.nests children under their parents
- 2.accepts a child listed before its parent
- 3.promotes an orphan to a root
- 4.returns an empty array for no rows
- 5.does not add children to the input rows
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.