简体   繁体   中英

JS Recursively find element in parent-child array

i have a array with a nested parent-child structure. I need to recursively go through this array and find wanted element. I wrote this function:

recursivelyFindElementByCondition(nodes, isSatisfyingCondition) {

    function recursiveCheck(items) {
        for (const item of items) {
            if (isSatisfyingCondition(item)) {
                return item;
            }

            if (item.rows) {
                recursiveCheck(item.rows)
            }
        }
    }

    return recursiveCheck(nodes);
}

But i don't understand why it returns undefined. It should work correct as far as i understand. I know that there is a way to create a variable out of scope of recursive function and assign element to it and then return it in the end, just wanted to do it without unnecessary variable and have no idea why is approach above doesn't work.

The result of the recursive call must be returned, for it to propagate up to the point of invocation and be returned as the result.

 function findNode(nodes, predicate) { for (const node of nodes) { if (predicate(node)) return node if (node.rows) { let match = findNode(node.rows, predicate) if (match) return match } } } const tree = [{ value: 'a', rows: [{ value: 'b' }] }, { value: 'c', rows: [{ value: 'd', rows: [{ value: 'e' }] }] }] const result = findNode(tree, ({value}) => value === 'e') console.log(result)

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