-
Notifications
You must be signed in to change notification settings - Fork 344
/
标题分组.js
105 lines (98 loc) · 2.08 KB
/
标题分组.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/**
需要输出
[{
"name": "h3"
}, {
"name": "h2",
"child": [{
"name": "h3"
}]
}, {
"name": "h1",
"child": [{
"name": "h2",
"child": [{
"name": "h3"
}, {
"name": "h3"
}]
}, {
"name": "h2",
"child": [{
"name": "h3"
}]
}]
}, {
"name": "h1",
"child": [{
"name": "h2",
"child": [{
"name": "h4"
}]
}, {
"name": "h2",
"child": [{
"name": "h3"
}]
}]
}]
*/
let list = [
'h3',
'h2', 'h3',
'h1', 'h2', 'h3', 'h3', 'h2', 'h3',
'h1', 'h2', 'h4', 'h2', 'h3'
]
function makeTree(arr) {
let tree = [];
let max = Infinity
let prev = {};
arr.forEach((title) => {
let level = Number(title[1]);
if (level <= max) {
let node = {
name: title,
};
tree.push(node);
prev.level = level;
prev.node = node;
max = level
} else if (level === prev.level) {
// 等级相同的话 上级节点的child继续增加子节点
prev = prev.prev;
pushNodeAndAdvanceQueue();
} else if (level > prev.level) {
pushNodeAndAdvanceQueue();
} else {
while (level <= prev.level) {
// 向上回溯,找到平级的再上一层node
prev = prev.prev;
}
pushNodeAndAdvanceQueue();
}
function pushNodeAndAdvanceQueue() {
let node = {
name: title,
};
if (!prev.node.child) {
let child = [];
prev.node.child = child;
}
prev.node.child.push(node);
let next = {
level,
node,
prev,
};
prev = next;
}
});
return tree;
}
console.log(makeTree(list));
/**
* 思路
*
* 利用链表来向上回溯合适的父节点
* 利用max变量记录当前分组的最大标题,如果比max还大,就需要新开一个分组了。
*/