Patan
Patan

Reputation: 17893

Return the value from nested loop java script

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.

Upvotes: 0

Views: 2194

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388406

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;
};

Upvotes: 4

Related Questions