11

I have the following scenario:

$.each(array, function() {
    ...
    $.each(array1, function() {
        if condition () { }
    });
});

How can I break out of outer each loop when my condition evaluates to true inside the inner each loop?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
okay
  • 173
  • 2
  • 10
  • possible duplicate of [Nested jQuery.each() - continue/break](http://stackoverflow.com/questions/3267508/nested-jquery-each-continue-break) – Ted Hopp Aug 28 '12 at 14:50
  • not its not, i only have to go with each loops not for loops. – okay Aug 28 '12 at 14:53
  • 1
    Look at some of the other answers there (like [this one](http://stackoverflow.com/a/3267627/535871)); they present solutions that maintain the use of `$.each`. – Ted Hopp Aug 28 '12 at 14:54
  • did u really think i would use the approach of throwing exceptions or using break..i want my code readable. the answer which is given below by Codesleuth solves my problem. – okay Aug 28 '12 at 14:57
  • 1
    The answer I linked to in my comment is essentially identical to that by Codesleuth. – Ted Hopp Aug 28 '12 at 15:07
  • With all due respect Mr. ted, question is same to the one you have linked, but the asnwers are not as i had expected. They are suggesting to use for loops, throw exceptions, use break statements which i dont want. Again, answer given by Codesleuth makes sense for me here. – okay Aug 28 '12 at 15:19
  • 1
    Did you look at the link in my second comment (a different answer to the same question)? That's the one that matches Codesleuth's. – Ted Hopp Aug 28 '12 at 15:21

2 Answers2

16
$.each(array, function() {
    var flag = true;

    $.each(array1, function() {
        if (condition) {
            flag = false;
            return false;
        }
    });

    return flag;
});
Codesleuth
  • 10,321
  • 8
  • 51
  • 71
  • 1
    If you reverse the sense of `flag` (so it is `true` when you want to continue the outer loop), then you can replace the last statement with `return flag;` (avoiding the `if` test). – Ted Hopp Aug 28 '12 at 14:53
  • Thanks Codesleuth, I'm going to mark it as answer as soon as stackoverflow time limit gets over. – okay Aug 28 '12 at 14:58
5

Set a value to test in the outer loop to exit

$.each(array, function() {
    var exit = false;
    $.each(array1, function() {
        if ( condition ) { 
           exit = true;
           return false;
        }
    }
    if (exit){
        return false;
    }
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Musa
  • 96,336
  • 17
  • 118
  • 137