Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

判断有无符合路径和 -> 打印所有路径 #46

Open
Sunny-117 opened this issue Nov 3, 2022 · 2 comments
Open

判断有无符合路径和 -> 打印所有路径 #46

Sunny-117 opened this issue Nov 3, 2022 · 2 comments

Comments

@Sunny-117
Copy link
Owner

const data3 = [
    {
        id: 1,
        name: '前端',
        children: [
            {
                id: 2,
                name: 'html',
                children: [
                    { id: 5, name: 'vue', children: [] },
                    { id: 6, name: 're', children: [] },
                ]
            },
            {
                id: 3,
                name: 'html',
                children: [
                    { id: 7, name: 'vue', children: [] },
                    { id: 8, name: 're', children: [] },
                ]
            }
        ]
    }
]
@kangkang123269
Copy link

function findNodePath(data, targetName) {
  let result = [];
  function dfs(node, path) {
    if (node.name === targetName) {
      result.push(path.concat(node.id));
    }
    if (node.children) {
      for (let child of node.children) {
        dfs(child, path.concat(node.id));
      }
    }
  }
  for (let node of data) {
    dfs(node, []);
  }
  return result;
}

console.log(findNodePath(data3, 'vue')); // [[1, 2, 5], [1, 3, 7]]
console.log(findNodePath(data3, 're')); // [[1, 2, 6], [1, 3, 8]]

@gswysy
Copy link

gswysy commented Mar 23, 2024

function fn(arr, name, path = '', res = []) {
    if (!arr) return null
    for (const item of arr) {
        if (item.name == name) {
            res.push(path ? path + '->' + item.id : item.id)
        } else {
            if (item.children && item.children.length) {
                fn(item.children, name, path ? path + '->' + item.id : item.id, res)
            }
        }
    }
    return res
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants