Skip to content

Commit 8894503

Browse files
committed
feat: 数组转树第二种方法
1 parent 40cecd0 commit 8894503

File tree

1 file changed

+38
-27
lines changed

1 file changed

+38
-27
lines changed

面试常见的手写题/05-数组转树.js

+38-27
Original file line numberDiff line numberDiff line change
@@ -103,34 +103,45 @@ let originalObj = [
103103

104104
// 1. 递归
105105
// 处理parentData 和childrenData 之间关系的函数
106-
function parseChildrenToParent(parentData, childrenData) {
107-
childrenData.forEach(item => {
108-
const tempData = parentData.find(_item => _item.id == item.pid);
109-
if (!tempData) return;
110-
tempData.children = tempData.children ?? [];
111-
tempData.children.push(item);
112-
// if (tempData.children) {
113-
// // 有值 递归
114-
// tempData.children.push(item);
115-
// } else {
116-
// tempData.children = [item];
117-
// }
118-
parseChildrenToParent([item], childrenData);
119-
});
120-
}
106+
// function parseChildrenToParent(parentData, childrenData) {
107+
// childrenData.forEach(item => {
108+
// const tempData = parentData.find(_item => _item.id == item.pid);
109+
// if (!tempData) return;
110+
// tempData.children = tempData.children ?? [];
111+
// tempData.children.push(item);
112+
// // if (tempData.children) {
113+
// // // 有值 递归
114+
// // tempData.children.push(item);
115+
// // } else {
116+
// // tempData.children = [item];
117+
// // }
118+
// parseChildrenToParent([item], childrenData);
119+
// });
120+
// }
121+
122+
// function arrayToTree(arr) {
123+
// let tree = [];
121124

122-
function arrayToTree(arr) {
123-
let tree = [];
125+
// function findParent(arr, pid = 0) {
126+
// const parentData = arr.filter(item => item.pid == 0),
127+
// childrenData = arr.filter(item => item.pid != 0);
128+
// parseChildrenToParent(parentData, childrenData);
129+
// tree = parentData;
130+
// }
124131

125-
function findParent(arr, pid = 0) {
126-
const parentData = arr.filter(item => item.pid == 0),
127-
childrenData = arr.filter(item => item.pid != 0);
128-
parseChildrenToParent(parentData, childrenData);
129-
tree = parentData;
130-
}
132+
// findParent(arr);
133+
// return tree;
134+
// }
131135

132-
findParent(arr);
133-
return tree;
134-
}
136+
// console.log(arrayToTree(originalObj));
137+
138+
// 2. 双重遍历
139+
const formatData = arr => {
140+
return arr.filter(item => {
141+
const _arr = arr.filter(_item => _item.pid == item.id);
142+
_arr.length && (item.children = _arr);
143+
return item.pid === 0;
144+
});
145+
};
135146

136-
console.log(arrayToTree(originalObj));
147+
console.log(formatData(originalObj));

0 commit comments

Comments
 (0)