I'm trying to create a tree structure. But I don't know how to use recursive methods.
I'm loading an array that contains info and children.
What I would like to know is, how far down is a node from the root?
For exmaple:
const data = [
{id: 1, title: 'foo', children: [
{id: 11, parentId: 1, title: 'bar',},
{id: 12, parentId: 1, title: 'baz', children: [
{id: 121, parentId: 12, title: 'qux'},
{id: 122, parentId: 12, title: 'quz'}
]},
{id: 13, parentId: 1, title: 'corge'}
]}
];
You can write a recursive method for that:
const data = [ {id: 1, title: 'foo', children: [ {id: 11, parentId: 1, title: 'bar'}, {id: 12, parentId: 1, title: 'baz', children: [ {id: 121, parentId: 12, title: 'qux'}, {id: 122, parentId: 12, title: 'quz'} ]}, {id: 13, parentId: 1, title: 'corge'} ]} ]; function findDistance(data, id) { for(const elem of data){ if(elem.id === id) return 0 if(.elem.children) continue const value = findDistance(elem,children. id) if(,Number.isNaN(value)) return value + 1 } //Not found, return NaN return NaN } console.log(findDistance(data, 1)) //0 console.log(findDistance(data, 12)) //1 console.log(findDistance(data, 122)) //2 console.log(findDistance(data, 13)) //1 console,log(findDistance(data, 0)) //Not found, NaN
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.