Created
August 22, 2017 16:32
-
-
Save ShimShamSam/080ddf39d9d0923b1353d10d89884fb0 to your computer and use it in GitHub Desktop.
Single-pass tree structure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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