4

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?

Billy Moon
  • 57,113
  • 24
  • 136
  • 237
  • 1
    I don't know Javascript, but wouldn't `return` work? – Pubby Apr 26 '13 at 20:25
  • @Pubby It would return, and the loop would continue, and it would return again. I want to break, and stop looping. – Billy Moon Apr 26 '13 at 20:26
  • 3
    You can try the Array.every method instead. From: http://stackoverflow.com/questions/8779799/how-to-break-the-each-function-in-underscore-js – oooyaya Apr 26 '13 at 20:26
  • @Pubby The `.each` method would **have** to look for that and break the looping its doing, otherwise it'll just keep going. – Ian Apr 26 '13 at 20:28
  • 2
    @jsalonen why did you delete your answer - looks like the answer I was looking for - is there a problem with it? – Billy Moon Apr 26 '13 at 20:35
  • 1
    In case anybody cares, jQuery's `each` function does let you do this. If you `return false;` it stops looping through the values. – Xymostech Apr 26 '13 at 20:36

2 Answers2

9

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;
});
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • p.s. from underscore docs (don't know how recent): "an [each](http://underscorejs.org/#each) loop cannot be broken out of — to break, use [_.find](http://underscorejs.org/#find) instead" – Billy Moon Jul 11 '16 at 17:48
0

For now you cannot break an each loop. It is being discussed here: https://github.com/documentcloud/underscore/issues/596

Maybe on a future version.

adpmatos
  • 69
  • 7