how to break the _.each function in underscore.js

JavascriptJqueryunderscore.js

Javascript Problem Overview


I'm looking for a way to stop iterations of underscore.js _.each() method, but can't find the solution. jQuery .each() can break if you do return false.

Is there a way to stop underscore each()?

_([1,2,3]).each(function(v){
    if (v==2) return /*what?*/;
})

Javascript Solutions


Solution 1 - Javascript

You can't break from the each method—it emulates the native forEach method's behavior, and the native forEach doesn't provide to escape the loop (other than throwing an exception).

However, all hope is not lost! You can use the Array.every method. :)

From that link:

>every executes the provided callback function once for each element present in the array until it finds one where callback returns a false value. If such an element is found, the every method immediately returns false.

In other words, you could do something convoluted like this (link to JSFiddle):

[1, 2, 3, 4].every(function(n) {
    alert(n);
    return n !== 3;
});

This will alert 1 through 3, and then "break" out of the loop.

You're using underscore.js, so you'll be pleased to learn that it does provide an every method—they call it every, but as that link mentions, they also provide an alias called all.

Solution 2 - Javascript

Update:

_.find would be better as it breaks out of the loop when the element is found:

var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var count = 0;
var filteredEl = _.find(searchArr,function(arrEl){ 
              count = count +1;
              if(arrEl.id === 1 ){
                  return arrEl;
              }
            });

console.log(filteredEl);
//since we are searching the first element in the array, the count will be one
console.log(count);
//output: filteredEl : {id:1,text:"foo"} , count: 1

** Old **

If you want to conditionally break out of a loop, use _.filter api instead of _.each. Here is a code snippet

var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var filteredEl = _.filter(searchArr,function(arrEl){ 
                  if(arrEl.id === 1 ){
                      return arrEl;
                  }
                });
console.log(filteredEl);
//output: {id:1,text:"foo"}

Solution 3 - Javascript

You can have a look to _.some instead of _.each. _.some stops traversing the list once a predicate is true. Result(s) can be stored in an external variable.

_.some([1, 2, 3], function(v) {
    if (v == 2) return true;
})

See http://underscorejs.org/#some

Solution 4 - Javascript

_([1,2,3]).find(function(v){
    return v if (v==2);
})

Solution 5 - Javascript

You cannot break a forEach in underscore, as it emulates EcmaScript 5 native behaviour.

Solution 6 - Javascript

Maybe you want Underscore's any() or find(), which will stop processing when a condition is met.

Solution 7 - Javascript

Like the other answers, it's impossible. Here is the comment about breaker in underscore underscore issue #21

Solution 8 - Javascript

I believe if your array was actually an object you could return using an empty object.

_.({1,2,3,4,5}).each(function(v){  
  if(v===3) return {}; 
});

Solution 9 - Javascript

> It's also good to note that an each loop cannot be broken out of — to > break, use _.find instead.

http://underscorejs.org/#each

Solution 10 - Javascript

Update:

You can actually "break" by throwing an error inside and catching it outside: something like this:

try{
  _([1,2,3]).each(function(v){
    if (v==2) throw new Error('break');
  });
}catch(e){
  if(e.message === 'break'){
    //break successful
  }
}

This obviously has some implications regarding any other exceptions that your code trigger in the loop, so use with caution!

Solution 11 - Javascript

worked in my case

var arr2 = _.filter(arr, function(item){
    if ( item == 3 ) return item;
});

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
Questiondy_View Question on Stackoverflow
Solution 1 - JavascriptaeskrView Answer on Stackoverflow
Solution 2 - JavascriptNikhilView Answer on Stackoverflow
Solution 3 - JavascriptJoanView Answer on Stackoverflow
Solution 4 - JavascriptRockyboy_rubyView Answer on Stackoverflow
Solution 5 - JavascriptJaredMcAteerView Answer on Stackoverflow
Solution 6 - JavascriptgrantwparksView Answer on Stackoverflow
Solution 7 - JavascriptczizzyView Answer on Stackoverflow
Solution 8 - Javascriptbm_iView Answer on Stackoverflow
Solution 9 - JavascriptpercebusView Answer on Stackoverflow
Solution 10 - Javascriptbm_iView Answer on Stackoverflow
Solution 11 - JavascriptaleXelaView Answer on Stackoverflow