0

Maybe a silly question, Is there a trick to correctly and easily place more than one return true/false in a nested if(){if(){if(){}}} statement?

Just an example:

One array: collection=[{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 },{"a":1,"b":1,"c":2}];

One object: source= { "a": 1, "c": 2 };

Question: use Array.filter(conditionFunc) to match element from source to collection: display those element with the same property and the same value from collection array. I have some code below but my question is:

1 Why I should return true here?

2 If there is a if(){if(){}}, where should I correctly return true?

the answer should return [{ "a": 1, "b": 2, "c": 2 },{"a":1,"b":1,"c":2}]

Wrong code below: Why the position to place "return true" after the first "return false" is wrong?

    var key=Object.keys(source);

    collection.filter(matchFun);

    function matchFun(item) {
        for (var i = 0; i < key.length; i++) {
            if (!item.hasOwnProperty(key[i]) || !source[[key[i]]] == item[key[i]]) {
                return false;
            }return true;  //this is wrong, but I don't know why?

        } 

    }

This is right code, but if there are more if(){} nested inside another if(){} I will get tripped where to "return true" the second time in different cases.Great thanks for anyone who can explain the mechanism to me

    key=Object.keys(source);

    collection.filter(matchFun);

    function matchFun(item) {
        for (var i = 0; i < key.length; i++) {
            if (!item.hasOwnProperty(key[i]) || !source[[key[i]]] == item[key[i]]) {
                return false;
            }

        } return true;

    }
Sophie cai
  • 195
  • 4
  • 13

1 Answers1

3

return causes the function to, well, return, which means the loop stops. The first case is wrong because you don't know to return false until after the loop has terminated w/o returning true.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101