javascript算法小结

1.扁平结构压成树形结构

http://stackoverflow.com/questions/12831746/javascript-building-a-hierarchical-tree

 1 var items = [
 2     {"Id": "1", "Name": "abc", "Parent": "2"},
 3     {"Id": "2", "Name": "abc", "Parent": ""},
 4     {"Id": "3", "Name": "abc", "Parent": "5"},
 5     {"Id": "4", "Name": "abc", "Parent": "2"},
 6     {"Id": "5", "Name": "abc", "Parent": ""},
 7     {"Id": "6", "Name": "abc", "Parent": "2"},
 8     {"Id": "7", "Name": "abc", "Parent": "6"},
 9     {"Id": "8", "Name": "abc", "Parent": "6"}
10 ];
11 
12 function buildHierarchy(arry) {
13 
14     var roots = [], children = {};
15 
16     // find the top level nodes and hash the children based on parent
17     for (var i = 0, len = arry.length; i < len; ++i) {
18         var item = arry[i],
19             p = item.Parent,
20             target = !p ? roots : (children[p] || (children[p] = []));
21 
22         target.push({ value: item });
23     }
24 
25     // function to recursively build the tree
26     var findChildren = function(parent) {
27         if (children[parent.value.Id]) {
28             parent.children = children[parent.value.Id];
29             for (var i = 0, len = parent.children.length; i < len; ++i) {
30                 findChildren(parent.children[i]);
31             }
32         }
33     };
34 
35     // enumerate through to handle the case where there are multiple roots
36     for (var i = 0, len = roots.length; i < len; ++i) {
37         findChildren(roots[i]);
38     }
39 
40     return roots;
41 }
42 
43 console.log(buildHierarchy(items));​
View Code
原文地址:https://www.cnblogs.com/353373440qq/p/4182021.html