Resolve Promises Sequentially
Run promises one after another and collect the results in order — built with .then chaining, no async/await.
JavaScript · ES6 — Pratik Rai ·
Turn a flat array of nodes with parentId into a nested tree — the shape behind every file explorer and nested menu.
Given a flat list of { id, name, parentId }, write buildTree(items) returning the roots of a tree.
Every node carries a children array. parentId is null for a root. Roots come back in the order they appeared. A child may be listed before its parent.
Input:
JSfile.javascript1buildTree([ 2 { id: 1, name: 'Parent', parentId: null }, 3 { id: 2, name: 'Child', parentId: 1 }, 4]);
Output:
[{ id: 1, name: 'Parent', parentId: null,
children: [{ id: 2, name: 'Child', parentId: 1, children: [] }] }]
The child is nested under the node whose id its parentId names.
APIs return flat rows because that is what a database returns. UIs need trees. This conversion sits behind every file explorer, comment thread and nested menu.
Build the lookup first, link second.
JSfile.javascript1function buildTree(items) { 2 const byId = new Map(); 3 items.forEach((item) => byId.set(item.id, { ...item, children: [] })); 4 const roots = []; 5 items.forEach((item) => { 6 const node = byId.get(item.id); 7 const parent = item.parentId === null ? undefined : byId.get(item.parentId); 8 if (parent) parent.children.push(node); 9 else roots.push(node); 10 }); 11 return roots; 12}
Doing it in two passes is what makes the input order irrelevant — a child listed before its parent still finds it, because every node exists in the map before any linking starts. A single pass that links as it goes has to handle the forward reference some other way.
Spreading each item into a new node rather than adding children to the caller's objects keeps the input clean, which matters when the same data feeds something else. Nodes whose parent is missing entirely are treated as roots rather than dropped, so nothing disappears silently.
Goal: Produce the roots of a correctly nested tree in one pass over a lookup.
children array. Then walk the list again and attach every node to its parent, collecting the ones with no parent as roots.Continue learning with these related challenges
Run promises one after another and collect the results in order — built with .then chaining, no async/await.
JavaScript · ES6 — Pratik Rai ·
Compare two values structurally, because === only ever compares references.
JavaScript · ES6 — Pratik Rai ·
Copy a nested structure so nothing is shared — including the cases that break a naive recursion.
JavaScript · ES6 — Pratik Rai ·
Run promises one after another and collect the results in order — built with .then chaining, no async/await.
JavaScript · ES6
Pratik Rai ·
Compare two values structurally, because === only ever compares references.
JavaScript · ES6
Pratik Rai ·
Copy a nested structure so nothing is shared — including the cases that break a naive recursion.
JavaScript · ES6
Pratik Rai ·