Wimal Weerawansa
Wimal Weerawansa

Reputation: 157

JS Tree search fails

I have Javascript tree structure

const tree = [
    {id: 120 , children:[]},
    {id: 110 , children:[
        {id: 12 , children:[
            {id: 3 , children:[]},
            {id: 4 , children:[]}
        ]}
    ]},
    {id: 10 , children:[
        {id: 13 , children:[]}
    ]}
    ]

and i have this function to find the parent of given node

const _findParent = (tree, component, _parent) => {
    let parent = null
    // iterate
    tree.forEach(node => {
        if(node.id === component.id){
            return _parent
        }

        parent = node. children ? _findParent(node.children, component, node) : parent

    })
    return parent
}

but it returns null, I cant find where i miss the parent object.

Upvotes: 0

Views: 34

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386570

Basically you check the children, but your children is always an array which is a truthy value. In this case, you could check if children is an array.

The use of Array#forEach does not work with a return value for using outside of the callback.

I suggest to use Array#some, which allows an early exit, which is necessary if a node is found.

Then I suggest to use a second variable for getting a nested result and if truthy, then assign to parent for return and exit the iteration.

const _findParent = (tree, component, _parent) => {
    let parent;
    tree.some(node => {
        var temp;
        if (node.id === component.id) {
            parent = _parent;
            return true;
        }
        temp = Array.isArray(node.children) && _findParent(node.children, component, node);
        if (temp) {
            parent = temp;
            return true;
        }
    });
    return parent;
}

const tree = [{ id: 120, children: [] }, { id: 110, children: [{ id: 12, children: [{ id: 3, children: [] }, { id: 4, children: [] }] }] }, { id: 10, children: [{ id: 13, children: [] }] }];

console.log(_findParent(tree, { id: 4 }));
console.log(_findParent(tree, { id: 42 }));

Upvotes: 2

Related Questions