Angular JS break ForEach

AngularjsJavascript Framework

Angularjs Problem Overview


I have an angular foreach loop and i want to break from loop if i match a value. The following code does not work.

angular.forEach([0,1,2], function(count){
  if(count == 1){
    break;
  }
});

How can i get this?

Angularjs Solutions


Solution 1 - Angularjs

The angular.forEach loop can't break on a condition match.

My personal advice is to use a NATIVE FOR loop instead of angular.forEach.

The NATIVE FOR loop is around 90% faster then other for loops.

For loop break , for loop test result

USE FOR loop IN ANGULAR:

var numbers = [0, 1, 2, 3, 4, 5];

for (var i = 0, len = numbers.length; i < len; i++) {
  if (numbers[i] === 1) {
    console.log('Loop is going to break.'); 
    break;
  }
  console.log('Loop will continue.');
}

Solution 2 - Angularjs

There's no way to do this. See https://github.com/angular/angular.js/issues/263. Depending on what you're doing you can use a boolean to just not going into the body of the loop. Something like:

var keepGoing = true;
angular.forEach([0,1,2], function(count){
  if(keepGoing) {
    if(count == 1){
      keepGoing = false;
    }
  }
});

Solution 3 - Angularjs

please use some or every instances of ForEach,

Array.prototype.some:
some is much the same as forEach but it break when the callback returns true

Array.prototype.every:
every is almost identical to some except it's expecting false to break the loop.

Example for some:

var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];

ary.some(function (value, index, _ary) {
    console.log(index + ": " + value);
    return value === "JavaScript";
});

Example for every:

var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];

ary.every(function(value, index, _ary) {
    console.log(index + ": " + value);
    return value.indexOf("Script") > -1;
});

Find more information
http://www.jsnoob.com/2013/11/26/how-to-break-the-foreach/

Solution 4 - Angularjs

Use the Array Some Method

 var exists = [0,1,2].some(function(count){
      return count == 1
 });

exists will return true, and you can use this as a variable in your function

if(exists){
    console.log('this is true!')
}

Array Some Method - Javascript

Solution 5 - Angularjs

As far as I know, Angular doesn't provide such a function. You may want to use underscore's find() function for this (it's basically a forEach which breaks out of the loop once the function returns true).

http://underscorejs.org/#find

Solution 6 - Angularjs

If you use jQuery (hence not jqLite) in conjunction with AngularJS you can iterate with $.each - which allows breaking and continuing based on boolean return value expression.

JSFiddle:

http://jsfiddle.net/JEcD2/1/

Javascript:

var array = ['foo', 'bar', 'yay'];
$.each(array, function(index, element){
    if (element === 'foo') {
        return true; // continue
    }
    console.log(this);
    if (element === 'bar') {
        return false; // break
    }
});

Note:

Though using jQuery is not bad, both native Array.some or Array.every functions are recommended by MDN as you can read at native forEach documentation:

> "There is no way to stop or break a forEach loop. The solution is to use Array.every or Array.some"

Following examples are provided by MDN:

Array.some:

function isBigEnough(element, index, array){
    return (element >= 10);
}
var passed = [2, 5, 8, 1, 4].some(isBigEnough);
// passed is false
passed = [12, 5, 8, 1, 4].some(isBigEnough);
// passed is true

Array.every:

function isBigEnough(element, index, array){
    return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].every(isBigEnough);
// passed is false
passed = [12, 54, 18, 130, 44].every(isBigEnough);
// passed is true

Solution 7 - Angularjs

Concretely, you can exit of a forEach loop, and of any place, throw an exception.

try {
   angular.forEach([1,2,3], function(num) {
      if (num === 2) throw Error();
   });
} catch(e) {
    // anything
}

However, it is better if you use other library or implement your own function, a find function in this case, so your code is most high-level.

Solution 8 - Angularjs

Try this as break;

angular.forEach([0,1,2], function(count){
  if(count == 1){
    return true;
  }
});

Solution 9 - Angularjs

As the other answers state, Angular doesn't provide this functionality. jQuery does however, and if you have loaded jQuery as well as Angular, you can use

jQuery.each ( array, function ( index, value) {
    if(condition) return false; // this will cause a break in the iteration
})

See http://api.jquery.com/jquery.each/

Solution 10 - Angularjs

Normally there is no way to break an "each" loop in javascript. What can be done usually is to use "short circuit" method.

    array.forEach(function(item) {
      // if the condition is not met, move on to the next round of iteration.
      if (!condition) return;

      // if the condition is met, do your logic here
      console.log('do stuff.')
    }

Solution 11 - Angularjs

break isn't possible to achieve in angular forEach, we need to modify forEach to do that.

$scope.myuser = [{name: "Ravi"}, {name: "Bhushan"}, {name: "Thakur"}];	
                angular.forEach($scope.myuser, function(name){
                  if(name == "Bhushan") {
                    alert(name);
                    return forEach.break(); 
                    //break() is a function that returns an immutable object,e.g. an empty string
                  }
                });

Solution 12 - Angularjs

You can use this:

var count = 0;
var arr = [0,1,2];
for(var i in arr){
   if(count == 1) break;
   //console.log(arr[i]);
}

Solution 13 - Angularjs

var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
var keepGoing = true;
ary.forEach(function(value, index, _ary) {
    console.log(index)
    keepGoing = true;
    ary.forEach(function(value, index, _ary) {
        if(keepGoing){ 
            if(index==2){
                keepGoing=false;
            }
            else{
                console.log(value)
            }
            
        }      
    });
});

    

Solution 14 - Angularjs

$scope.arr = [0, 1, 2];  
$scope.dict = {}
for ( var i=0; i < $scope.arr.length; i++ ) {
    if ( $scope.arr[i] == 1 ) {
        $scope.exists = 'yes, 1 exists';
        break;
    }
 }
 if ( $scope.exists ) {
     angular.forEach ( $scope.arr, function ( value, index ) {
                      $scope.dict[index] = value;
     });
 }

Solution 15 - Angularjs

I would prefer to do this by return. Put the looping part in private function and return when you want to break the loop.

Solution 16 - Angularjs

This example works. Try it.

var array = [0,1,2];
for( var i = 0, ii = array.length; i < ii; i++){
  if(i === 1){
   break;
  }
}

Solution 17 - Angularjs

I realise this is old, but an array filter may do what you need:

var arr = [0, 1, 2].filter(function (count) {
    return count < 1;
});

You can then run arr.forEach and other array functions.

I realise that if you intend to cut down on loop operations altogether, this will probably not do what you want. For that you best use while.

Solution 18 - Angularjs

I would use return instead of break.

angular.forEach([0,1,2], function(count){
  if(count == 1){
    return;
  }
});

Works like a charm.

Solution 19 - Angularjs

Use Return to break the loop.

angular.forEach([0,1,2], function(count){
  if(count == 1) {
    return;
  }
});

Solution 20 - Angularjs

onSelectionChanged(event) {
    let selectdata = event['api']['immutableService']['gridOptionsWrapper']['gridOptions']['rowData'];
    let selected_flag = 0;

    selectdata.forEach(data => {
      if (data.selected == true) {
        selected_flag = 1;
      }
    });

    if (selected_flag == 1) {
      this.showForms = true;
    } else {
      this.showForms = false;
    }
}

Solution 21 - Angularjs

Just add $index and do the following:

angular.forEach([0,1,2], function(count, $index) {
     if($index !== 1) {
          // do stuff
     }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChubby BoyView Question on Stackoverflow
Solution 1 - AngularjsNishchitView Answer on Stackoverflow
Solution 2 - Angularjsdnc253View Answer on Stackoverflow
Solution 3 - AngularjsNeo VijayView Answer on Stackoverflow
Solution 4 - AngularjsAman FahimullahView Answer on Stackoverflow
Solution 5 - AngularjsmnaView Answer on Stackoverflow
Solution 6 - AngularjsconceptdeluxeView Answer on Stackoverflow
Solution 7 - AngularjsVictor AguilarView Answer on Stackoverflow
Solution 8 - AngularjspanatoniView Answer on Stackoverflow
Solution 9 - AngularjsNik DowView Answer on Stackoverflow
Solution 10 - AngularjsDownhillskiView Answer on Stackoverflow
Solution 11 - Angularjsrb4bhushanView Answer on Stackoverflow
Solution 12 - AngularjsendrcnView Answer on Stackoverflow
Solution 13 - Angularjsuser1693371View Answer on Stackoverflow
Solution 14 - Angularjssolanki...View Answer on Stackoverflow
Solution 15 - AngularjsPrabaharanKathiresanView Answer on Stackoverflow
Solution 16 - AngularjsMaikel RosabalView Answer on Stackoverflow
Solution 17 - AngularjsShorelineView Answer on Stackoverflow
Solution 18 - AngularjsAakashView Answer on Stackoverflow
Solution 19 - AngularjsShanmugarajanView Answer on Stackoverflow
Solution 20 - Angularjspoovarasi sekarView Answer on Stackoverflow
Solution 21 - AngularjsSultanView Answer on Stackoverflow