深度优先查询、广度优先查询、扁平化数组变成树
程序员文章站
2022-03-03 11:49:15
...
深度优先查询、广度优先查询、扁平化数组变成树
深度广度数据
const arr = [
{
id: 1,
label: "一级 1",
children: [
{
id: 4,
label: "二级 1-1",
children: [
{
id: 9,
label: "三级 1-1-1",
},
],
},
],
},
{
id: 2,
label: "一级 2",
children: [
{
id: 5,
label: "二级 2-1",
children: [
{
id: 10,
label: "三级 2-1-1",
},
],
},
{
id: 6,
label: "二级 2-2",
children: [
{
id: 11,
label: "三级 2-2-1",
},
],
},
],
},
{
id: 3,
label: "一级 3",
children: [
{
id: 7,
label: "二级 3-1",
children: [
{
id: 12,
label: "三级 3-1-1",
},
],
},
{
id: 8,
label: "二级 3-2",
children: [
{
id: 13,
label: "三级 3-2-1",
},
],
},
],
},
];
深度优先查询
const id = 9;
function shendu(currentTree) {
for (let i = 0; i < currentTree.length; i++) {
if (currentTree[i].id !== id) {
if (currentTree[i].children) {
shendu(currentTree[i].children);
}
} else {
console.log(currentTree[i]);
break;
}
}
}
shendu(arr);
广度优先查询
function guangdu() {
let current;
const queue = [...arr];
for (let i = 0; i < queue.length; i++) {
current = queue[i];
if (current.id !== 9) {
if (current.children) {
queue.push(...current.children);
}
} else {
break;
}
}
console.log(current);
}
扁平化数组变成树
const list: [
{ pid: -1, name: "购物车", id: 1, auth: "cart" },
{ pid: 1, name: "购物车列表", id: 4, auth: "cart-list" },
{ pid: 4, name: "**", id: 5, auth: "lottery" },
{ pid: 4, name: "商品", id: 6, auth: "product" },
{ pid: -1, name: "商店", id: 2, auth: "shop" },
{ pid: -1, name: "个人中心", id: 3, auth: "store" },
],
const getTree = (tree) => {
const newList = [];
for (let i = 0; i < tree.length; i++) {
if (tree[i].pid === -1) {
newList.push(tree[i]);
} else {
const findItem = tree.find((item) => item.id === tree[i].pid);
if (findItem) {
if (findItem.children) {
// 更改原数组就相当于给新数组里面添加了children,因为新数组里面元素的地址和原数组是一个、
findItem.children.push(tree[i]);
} else {
findItem.children = [tree[i]];
}
}
}
}
return newList;
};
getTree(arr)