Open Rain120 opened 2 years ago
const getPosByIdInTree = (tree, id) => {
const res = [];
if (tree.id === id) {
return [0];
}
const find = (currentTree, sourceId) => {
if (currentTree.id === sourceId) {
res.push(0);
return;
}
if (!currentTree.children) {
return;
}
currentTree.children.forEach((child, index) => {
if (child.id === sourceId) {
res.push(index);
// 回到父级查找
find(tree, currentTree.id);
} else {
// 继续找其他子项
find(child, sourceId);
}
});
};
find(tree, id);
return res.reverse();
};
从数组中寻找指定元素的路径
const getPosByIdInTree = (tree,id)=>{
const res = [];
if (tree.id === id) {
return [0];
}
const find = (currentTree,sourceId)=>{
if (currentTree.id === sourceId) {
return;
}
if (!currentTree.sub) {
return;
}
currentTree.sub.forEach((child,index)=>{
if (child.id === sourceId) {
res.push(index);
// 回到父级查找
find(tree, currentTree.id);
} else {
// 继续找其他子项
find(child, sourceId);
}
}
);
}
;
find(tree, id);
return res.reverse();
}
;
const findPath = (arr,id)=>{
arr.forEach((val,i)=>{
const res = getPosByIdInTree(val, id);
if (res.length) {
console.log([i, ...res])
}
}
);
}
const data = [
{
id: '1',
sub: [
{
id: '2',
sub: [
{
id: '3',
sub: null,
},
{
id: '4',
sub: [
{
id: '6',
sub: null,
},
],
},
{
id: '5',
sub: null,
},
],
},
],
},
{
id: '7',
sub: [
{
id: '8',
sub: [
{
id: '9',
sub: null,
},
{
id: '12',
sub: [
{
id: '128',
sub: [
{
id: '129',
sub: null,
},
{
id: '9527',
sub: null,
},
],
},
],
},
],
},
],
},
{
id: '10',
sub: null,
},
];
findPath(data, '9527');
题目