set24

Build a category tree from a flat list

24 / 26
read the snippet · pick its Big-O
// rows: [{ id, parentId, name }, ]. Top-level rows have parentId = null.
function buildTree(rows) {
const roots = [];
for (const row of rows) {
if (row.parentId == null) {
roots.push({ row, children: [] });
}
}
function attach(node) {
for (const row of rows) {
if (row.parentId === node.id) {
const child = { row, children: [] };
node.children.push(child);
attach(child);
}
}
}
for (const root of roots) attach(root);
return roots;
}