记录一次 无法做出来的面试题

输入

let 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: 4},
]

输出

[
    {
        "id": 1,
        "name": "部门1",
        "pid": 0,
        "children": [
            {
                "id": 2,
                "name": "部门2",
                "pid": 1,
                "children": []
            },
            {
                "id": 3,
                "name": "部门3",
                "pid": 1,
                "children": [
                    // 结果 ,,,
                ]
            }
        ]
    }
]

children中放置id和pid匹配项

后续无意在掘金上面发现了这个答案,当时以为这题很简单的,没想到一上机就…

let arr = [
    {id: 1, name: '部门1', pid: 9},
    {id: 2, name: '部门2', pid: 1},
    {id: 3, name: '部门3', pid: 1},
    {id: 4, name: '部门4', pid: 3},
    {id: 5, name: '部门5', pid: 4},
];
let a = new Map();
let b = [];
arr = arr.sort((a,b)=>a.pid-b.pid);
for(let item of arr){
const value = {...item,children:[]};
if(!a.has(item.pid)){
b.push(value);
a.set(item.id,value);
}else{
const srouce = a.get(item.pid);
srouce.children.push(value);
a.set(item.id,value)
}
}

个人觉得面试前刷题包装自己是非常不好的,经验都是在项目和实战中总结出来的。

上一篇:js实现树级递归


下一篇:写屏障(write barrier)