// 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},
// ]
function arrToTree(arr) {
let result = []
let first = arr[0]
arr.shift()
if(arr instanceof Array && arr.length) {
let f = arr.filter(d => d.pid === first.id)
first.children = []
if(f.length) {
f.map(fd => {
fd.children = []
first.children.push(fd)
})
arr = arr.filter(d => d.pid !== first.id)
let temp = arrToTree(arr)
f.map((d,i) =>{
if(temp.length && d.id === temp[0].pid) {
f[i].children = temp
}
})
result.push(first)
} else {
first.children = arrToTree(arr)
}
}
return result
}
function test(){
let random = randomArr()
let _t1 = performance.now();
let tree = arrToTree(random)
let _t2 = performance.now();
console.log(_t2 - _t1);
}
function randomArr() {
let arr = []
for(let i=0; i< 1000; i++) {
let randNum1 = Math.floor(Math.random() * 10)
let randNum2 = Math.floor(Math.random() * 10)
let randNum3 = Math.floor(Math.random() * 10)
arr.push({
id: randNum1,
name: '部门'+randNum2,
pid: randNum3,
})
}
return arr
}
test()
console