简体   繁体   中英

How to find a tree inside a tree in typescript

let say i have a tree in javascript

a1 
--b
----c1
a2
--b2
--b3
----c2

and if i wanted to find c2, it should return a2->b3->c2

Lets say my json looked like this?

treeFamily = {
            name : "Parent",
            children: [{
                name : "Child1",
                children: [{
                    name : "Grandchild1",
                    children: []
                },{
                    name : "Grandchild2",
                    children: []
                },{
                    name : "Grandchild3",
                    children: []
                }]
            }, {
                name: "Child2",
                children: []
            }]
        };

You could check if the nested children have the wanted key/value. Then take the name and hand over the result to the outer call.

 function findPath(array, target) { var path; array.some(({ name, children }) => { var temp; if (name === target) { path = [name]; return true; } if (temp = findPath(children, target)) { path = [name, ...temp]; return true; } }); return path; } var treeFamily = { name: "Parent", children: [{ name: "Child1", children: [{ name: "Grandchild1", children: [] }, { name: "Grandchild2", children: [] }, { name: "Grandchild3", children: [] }] }, { name: "Child2", children: [] }] }; console.log(findPath([treeFamily], 'Grandchild2')); console.log(findPath([treeFamily], 'foo')); 

You can use for...of to search the children by calling the function recursively. If the target is found, the name is returned, and combined with the previous names. If not, the function will return undefined . Alternatively, you can return an empty array.

 const findPath = (targetName, { name, children }) => { if(name === targetName) return [name]; for(const child of children) { const result = findPath(targetName, child); if(result) return [name, ...result]; } // if child not found implicitly return undefined or return [] to get an empty array }; const treeFamily = { name: "Parent", children: [{ name: "Child1", children: [{ name: "Grandchild1", children: [] }, { name: "Grandchild2", children: [] }, { name: "Grandchild3", children: [] }] }, { name: "Child2", children: [] }] }; console.log(findPath('Child2', treeFamily)); console.log(findPath('Grandchild3', treeFamily)); console.log(findPath('Grandchild400', treeFamily)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM