题目:
将一个一维数组转成tree结构数组
输入该数组:
const arr = [
{ id: 1, name: "部门1", pid: 0 },
{ id: 2, name: "部门2", pid: 1 },
{ id: 3, name: "部门3", pid: 1 },
{ id: 4, name: "部门4", pid: 3 },
{ id: 5, name: "部门5", pid: 3 },
{ id: 6, name: "部门6", pid: 3 },
{ id: 8, name: "部门8", pid: 7 },
{ id: 10, name: "部门10", pid: 9 },
];
为了追求性能,就应该排除掉递归这种方案; 直接考虑最优方案:
function arrToTree(arr) {
// 这样写,考虑到万一传进来的不是数组,是undefined ,可以返回空数组,避免报错
if (!arr) {
return [];
}
const map = new Map();
const result = [];
for (const node of arr) {
// 将数组整理成Map结构【不了解Map结构的,可以先去学习Map用法】
map.set(node.id, { ...node, children: [] });
}
for (const node of arr) {
// 缓存当前节点
const cur = map.get(node.id);
// 看能否找到父节点,
const parent = map.get(node.pid);
// 当有parent时,就应该往children里面push当前节点就好
if (parent) {
parent.children.push(cur);
} else {
// 没有话,直接往最外层push
result.push(cur);
}
}
return result;
}