0

How would I go about creating a recursive function that can search through a list for a node where x = 10?

I do not have any javascript experience so I am not sure where to start so would appreciate and input

I have come across the following code and tried to adapt it but I am not sure if I am on the right track:

function search(_for, _in) {
    var r;
    for (var p in _in) {
        if ( p === 10 ) {
            return _in[p];
        }
        if ( typeof _in[p] === 'object' ) {
            if ( (r = search(_for, _in[p])) !== null ) {
                return r;
            }
        }
    }
    return null;
}

Thank you in advance

1 Answer 1

1

Try this

var finder = function(needle, haystack) {
    if (haystack.length == 0) 
        return false

    if (haystack[0] == needle)
        return true

    return finder(pin, haystack.slice(1))
}

Or

var finder = function(pin, haystack) {
    return (haystack[0] == pin) || (haystack.length != 0) && finder(pin, haystack.slice(1)) 
}

Recursion FTW

Sign up to request clarification or add additional context in comments.

2 Comments

Thank @Simon but if I may ask how does it know that X should be 10 if there is no 10 in the code? Sorry for asking, I am just trying to understand it as I go along
finder(needle, haystack) searches for needle in haystack, so you can just use finder(10, haystack) unless I misunderstood your question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.