0

I have written a function which is involving multiple loops.

$scope.matchFunction = function() {
    angular.forEach(datas, function(data) {
      angular.forEach(data.innerdatas, function(nnerdata) {
        if (innerdata.id === 'ABCD') {
          console.log('matched');
          //matched return true and break and stop executon
          return true;
        }
      });
    });
   return false;
};

But I am always ending up in returning false.

I think I am not able to return from nested loops.

Any help.

1 Answer 1

4

You are not returning from the main function, you are returning the value only from the inner function.

You can use a variable to store the state and then can return it like

$scope.matchFunction = function () {
    var valid = false;
    angular.forEach(datas, function (data) {
        angular.forEach(data.innerdatas, function (nnerdata) {
            if (innerdata.id === 'ABCD') {
                console.log('matched');
                //matched return true and break and stop executon
                valid = true;
            }
        });
    });
    return valid;
};
Sign up to request clarification or add additional context in comments.

1 Comment

You should also return from inside if block also, just to overcome unnecessary iteration.

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.