Created
June 11, 2019 06:43
-
-
Save buddalee/7d67dff04904251a73822486735a3518 to your computer and use it in GitHub Desktop.
here is one in O(n log n) time treeify
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
const flattenArr = [ | |
{ title: '首頁', id: 11, parent_id: 0, children: [] }, | |
{ title: '子頁', id: 12, parent_id: 11, children: [] }, | |
{ title: '產品頁', id: 21, parent_id: 0, children: [] } | |
] | |
function treeify(nodes) { | |
var indexed_nodes = {}, tree_roots = []; | |
for (var i = 0; i < nodes.length; i += 1) { | |
indexed_nodes[nodes[i].id] = nodes[i]; | |
} | |
for (var i = 0; i < nodes.length; i += 1) { | |
var parent_id = nodes[i].parent_id; | |
if (parent_id === 0) { | |
tree_roots.push(nodes[i]); | |
} else { | |
indexed_nodes[parent_id].children.push(nodes[i]); | |
} | |
} | |
return tree_roots; | |
} | |
console.log(JSON.stringify(treeify(nodes), undefined, "\t")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment