Himmators
Himmators

Reputation: 15006

Can I break an _each from inside another _each?

I'm new to underscore. For the outer _each-loop, I wish to count the conversions only once. In other words, I would like it to stop after the first conversion.y++. Is this possible?

_.each(conversions, function(conversion){
 _.each(user.apilog, function(event){
        if( conversion.conditional(event) ){
            conversion.y++;
        }
    })
})

Upvotes: 1

Views: 170

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276306

Quoting the underscore docs:

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

So no, it can't be broken from - their recommendation is to use .find - which breaks on the first truthy value you return from it - that won't help you in nested each though so you can either set a flag:

var flag = false;;
_.find(conversions, function(conversion){
 _.find(user.apilog, function(event){
        if( conversion.conditional(event) ){
            conversion.y++;
            return flag = true;
        }
    });
    return flag;
});

Or not use a nested _.each loop, one elegant approach would be to use a cartesian product:

   var prod = cartProd(conversations, user.apilog);
   _.find(prod, function(item){
        return item[0].conditional(item[1]); // will break on find
   });

Although a plain old JS for loop would also work and would likely be faster.

Upvotes: 2

Related Questions