Skip to content

Instantly share code, notes, and snippets.

@ShimShamSam
Created August 22, 2017 16:32
Show Gist options
  • Save ShimShamSam/080ddf39d9d0923b1353d10d89884fb0 to your computer and use it in GitHub Desktop.
Save ShimShamSam/080ddf39d9d0923b1353d10d89884fb0 to your computer and use it in GitHub Desktop.
Single-pass tree structure
function createTree(nodes) {
const children = {};
const tree = [];
for(const node of nodes) {
node.children = children[node.id] || (children[node.id] = []);
(node.parent_id ? children[node.parent_id] || (children[node.parent_id] = []) : tree).push(node);
}
return tree;
}
var nodes = [
{
id : 1,
parent_id : null,
},
{
id : 2,
parent_id : 1,
},
{
id : 3,
parent_id : 4,
},
{
id : 4,
parent_id : 2,
},
{
id : 5,
parent_id : 2,
}
];
console.log(JSON.stringify(createTree(nodes), null, 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment