Skip to content
Advertisement

Recursively Search in Array with a For Loop

I know there are better ways to search an array, but I really want to understand how to return when the value is found in a recursive call. Logging when found isn’t a problem, but I can’t seem to make this return true when found.

The problem is basic. Fully search multi-dimensional array for a value and return true if found or false if not found, using a for loop and recursion. I’ve tried returning the recursive function and everything else I can think of, but nothing works fully.

function lookForKey( arr ){
    for ( let i = 0; i < arr.length; i++ ) {
        if( arr[i] == "key" ){
            console.log( "Key found.");
            return true;
        } else if( Array.isArray( arr[i] ) ){
            lookForKey( arr[i] );
        }
    }

    return false;
}

let arr = [
    ["foo", "bar"],
    ["foo", "bar", "key"]
];

console.log( lookForKey( arr ) );

I appreciate any insight on this!

Advertisement

Answer

function lookForKey( arr ){
    for ( let i = 0; i < arr.length; i++ ) {
        if( arr[i] == "key" ){
            console.log( "Key found.");
            return true;
        } else if( Array.isArray( arr[i] ) ){
            if (lookForKey(arr[i])) return true;
        }
    }

    return false;
}

let arr = [
    ["foo", "bar"],
    ["foo", "bar", "key"]
];

console.log( lookForKey( arr ) );

So two changes. First, you have to have the return on the recursive call. However, if the recursive call returns false, you don’t want to return immediately from the caller. You want to continue the loop. So you can make that a conditional and only return true if the recursive call returns true.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement