Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break and return from recursive functions?

Using the following code, the function returns several times. I need to break the recursion and return the result only once.

Any idea how to fix it?

http://jsfiddle.net/xhe6h8f0/

var data = {
    item: [{
        itemNested: [{
            itemNested2: [{
                id: "2"
            }]
        }]
    }]
};

function findById (obj, id) {
        var result;
        for (var p in obj) {
            if (obj.id) {
                if(obj.id == id) {
                    result = obj;
                    break; // PROBLEM HERE dos not break
                }
            } else {
                if (typeof obj[p] === 'object') {
                    findById(obj[p], id);
                }
            }
        }
        console.log(result);
        return result;
}
var result = findById(data, "2");
alert(result);
like image 239
GibboK Avatar asked Dec 15 '14 13:12

GibboK


People also ask

How do you break a recursive function?

One way to break out of a recursive function in Python is to throw an exception and catch that at the top level. Some people will say that this is not the right way to think about recursion, but it gets the job done.

How do you stop a recursion in Python?

You can make use of the class. Initialize a variable self. flag=False in the init method, when you find the solution change self. flag = True and return None when self.

How do you stop a recursive loop?

Use a return; statement where the code needs to stop and go back to its predecessor (which will in turn also call the return; , and so on...)


1 Answers

If the match is found, then you need to return the value. And in the parent call, if the recursive call returns a value, then it also has to return that value. You can modify your code like this

function findById(obj, id) {
    var result;
    for (var p in obj) {
        /*
           if `id` is not in `obj`, then `obj.id` will evaluate to
           be `undefined`, which will not be equal to the `id`.
        */
        if (obj.id === id) {
            return obj;
        } else {
            if (typeof obj[p] === 'object') {
                result = findById(obj[p], id);
                if (result) {
                    return result;
                }
            }
        }
    }
    return result;
}

Now,

var result = findById(data, "2");
console.log(result);

will print

{ id: '2' }
like image 111
thefourtheye Avatar answered Sep 23 '22 03:09

thefourtheye