Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking out of an inner foreach loop

I am trying to break out of an inner foreach loop using JavaScript/jQuery.

result.history.forEach(function(item) {
    loop2:
    item.forEach(function(innerItem) {
        console.log(innerItem);
        break loop2;
    });
}); 

This is resulting in the error 'Unidentified label loop2'. it appears to be right before the loop which was what other questions were saying was the issue.

What am I doing wrong and how do I fix it?

Edit: Correct, the foreach loop cant break in this way but a regular for loop can. This is working:

                        result.history.forEach(function(item) {
                            loop2:
                            for (var i = 0; i < item.length; i++) {
                                var innerItem = item[i];
                                console.log(innerItem);
                                break loop2;
                            }
                        });
like image 711
David Tunnell Avatar asked Dec 22 '15 22:12

David Tunnell


People also ask

How do you break inner forEach loop?

Iirc a break; statement will only break the closest loop, so issuing a break; in the inner loop should continue with the next item on the outer loop. The OP wants to skip the remaining code on the outer loop and continue its execution at the top of the outer loop.

Can you break out of a for of loop?

To break out of a for loop, you can use the endloop, continue, resume, or return statement. endfor; If condition is true, statementlist2 is not executed in that pass through the loop, and the entire loop is closed.

How do you break out of inner loop and continue outer loop?

Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.

Does return break out of forEach?

'return' doesn't stop looping The reason is that we are passing a callback function in our forEach function, which behaves just like a normal function and is applied to each element no matter if we return from one i.e. when element is 2 in our case.


1 Answers

If you need to be able to break an iteration, use .every() instead of .forEach():

someArray.every(function(element) {
  if (timeToStop(element)) // or whatever
    return false;
  // do stuff
  // ...
  return true; // keep iterating
});

You could flip the true/false logic and use .some() instead; same basic idea.

like image 100
Pointy Avatar answered Oct 05 '22 22:10

Pointy