Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break out of an _.each loop

Is it possible to break out of an underscore each loop..?

_.each(obj, function(v,i){
  if(i > 2){
    break // <~ does not work
  }
  // some code here
  // ...
})

Is there another design pattern I can be using?

like image 699
Billy Moon Avatar asked Jan 13 '23 13:01

Billy Moon


1 Answers

I don't think you can, so you will just have to wrap the contents of the function in i < 2 or use return. It may make more sense to use .some or .every.

EDIT:

//pseudo break
_.each(obj, function (v, i) {
    if (i <= 2) {
        // some code here
        // ...
    }
});

The issue with the above is of course that it has to do the entire loop, but that is simply a weakness of underscore's each.

You could use .every, though (either native array method or underscore's method):

_.every(obj, function (v, i) {
    // some code here
    // ...
    return i <= 2;
});
like image 55
Explosion Pills Avatar answered Jan 17 '23 07:01

Explosion Pills