Skip to content Skip to sidebar Skip to footer

Javascript Tree Search Algorithm Which Return Subset Of The Tree Which Contains The Found Term And Its Parents

I have a tree selection in which every node has a name. I want to search through the node names and return a subset of the tree which only contains the found nodes and its parents.

Solution 1:

I guess that's what you're looking for:

search = node => {
    let found, { name, childs = [] } = node;

    if (childs.length)
        for (let child of node.childs)
            if (found = search(child))
                return [name].concat(found);

    return name === target && [name];
}

And here is my full solution:

const// Your animal target name
    target = 'Elephant',

    // Your tree data structure
    tree = [
        { name: 'Elephant', childs: [
            { name: 'Duck' },
            { name: 'Hamster', childs: [
                { name: 'Fish' }
            ]}
        ]},
        { name: 'Hamster', childs: [
            { name: 'Elephant', childs: [
                { name: 'Fish' }
            ]},
            { name: 'Dog', childs: [
                { name: 'Fish' }
            ]}
        ]},
        { name: 'Dog', childs: [
            { name: 'Unicorn' },
            { name: 'Fish', childs: [
                { name: 'Hamster' },
                { name: 'Unicorn', childs: [
                    { name: 'Elephant' }
                ]},
            ]}
        ]},
        { name: 'Elephant', childs: [
            { name: 'Duck' },
            { name: 'Hamster', childs: [
                { name: 'Elephant' },
                { name: 'Fish' },
            ]}
        ]}
    ],

    // The recursive tree search function. Her exit point is// a child who matches the target. He returns the path to// target - if found - as an array. Otherwise, false
    search = node => {
        let found, { name, childs = [] } = node;

        if (childs.length)
            for (let child of node.childs)
                if (found = search(child))
                    return [name].concat(found);

        return name === target && [name];
    },

    // The result, as a set of arrays. We filter out the// branches that do not contain the result
    result = tree.map(search).filter(Boolean);

    // The result as a formatted string for easy viewing
    formattedResult = result.map((path, index) =>`${index + 1}: ${path.join(' > ')}`).join('\n');

console.log(formattedResult);

Post a Comment for "Javascript Tree Search Algorithm Which Return Subset Of The Tree Which Contains The Found Term And Its Parents"