Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 months ago.
Improve this question
What's the best way to break from nested loops in Javascript?
//Write the links to the page.
for (var x = 0; x < Args.length; x++)
{
for (var Heading in Navigation.Headings)
{
for (var Item in Navigation.Headings[Heading])
{
if (Args[x] == Navigation.Headings[Heading][Item].Name)
{
document.write("<a href=\""
+ Navigation.Headings[Heading][Item].URL + "\">"
+ Navigation.Headings[Heading][Item].Name + "</a> : ");
break; // <---HERE, I need to break out of two loops.
}
}
}
}
Just like Perl,
loop1:
for (var i in set1) {
loop2:
for (var j in set2) {
loop3:
for (var k in set3) {
break loop2; // breaks out of loop3 and loop2
}
}
}
as defined in EMCA-262 section 12.12. [MDN Docs]
Unlike C, these labels can only be used for continue and break, as Javascript does not have goto.
Wrap that up in a function and then just return.
I'm a little late to the party but the following is a language-agnostic approach which doesn't use GOTO/labels or function wrapping:
for (var x = Set1.length; x > 0; x--)
{
for (var y = Set2.length; y > 0; y--)
{
for (var z = Set3.length; z > 0; z--)
{
z = y = -1; // terminates second loop
// z = y = x = -1; // terminate first loop
}
}
}
On the upside it flows naturally which should please the non-GOTO crowd. On the downside, the inner loop needs to complete the current iteration before terminating so it might not be applicable in some scenarios.
I realize this is a really old topic, but since my standard approach is not here yet, I thought I post it for the future googlers.
var a, b, abort = false;
for (a = 0; a < 10 && !abort; a++) {
for (b = 0; b < 10 && !abort; b++) {
if (condition) {
doSomeThing();
abort = true;
}
}
}
Quite simple:
var a = [1, 2, 3];
var b = [4, 5, 6];
var breakCheck1 = false;
for (var i in a) {
for (var j in b) {
breakCheck1 = true;
break;
}
if (breakCheck1) break;
}
Here are five ways to break out of nested loops in JavaScript:
1) Set parent(s) loop to the end
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
{
i = 5;
break;
}
}
}
2) Use label
exit_loops:
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
break exit_loops;
}
}
3) Use variable
var exit_loops = false;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
{
exit_loops = true;
break;
}
}
if (exit_loops)
break;
}
4) Use self executing function
(function()
{
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
return;
}
}
})();
5) Use regular function
function nested_loops()
{
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
return;
}
}
}
nested_loops();
var str = "";
for (var x = 0; x < 3; x++) {
(function() { // here's an anonymous function
for (var y = 0; y < 3; y++) {
for (var z = 0; z < 3; z++) {
// you have access to 'x' because of closures
str += "x=" + x + " y=" + y + " z=" + z + "<br />";
if (x == z && z == 2) {
return;
}
}
}
})(); // here, you execute your anonymous function
}
How's that? :)
How about using no breaks at all, no abort flags, and no extra condition checks. This version just blasts the loop variables (makes them Number.MAX_VALUE) when the condition is met and forces all the loops to terminate elegantly.
// No breaks needed
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
if (condition) {
console.log("condition met");
i = j = Number.MAX_VALUE; // Blast the loop variables
}
}
}
There was a similar-ish answer for decrementing-type nested loops, but this works for incrementing-type nested loops without needing to consider each loop's termination value for simple loops.
Another example:
// No breaks needed
for (var i = 0; i < 89; i++) {
for (var j = 0; j < 1002; j++) {
for (var k = 0; k < 16; k++) {
for (var l = 0; l < 2382; l++) {
if (condition) {
console.log("condition met");
i = j = k = l = Number.MAX_VALUE; // Blast the loop variables
}
}
}
}
}
If you use Coffeescript, there is a convenient "do" keyword that makes it easier to define and immediately execute an anonymous function:
do ->
for a in first_loop
for b in second_loop
if condition(...)
return
...so you can simply use "return" to get out of the loops.
I thought I'd show a functional-programming approach. You can break out of nested Array.prototype.some() and/or Array.prototype.every() functions, as in my solutions. An added benefit of this approach is that Object.keys() enumerates only an object's own enumerable properties, whereas "a for-in loop enumerates properties in the prototype chain as well".
Close to the OP's solution:
Args.forEach(function (arg) {
// This guard is not necessary,
// since writing an empty string to document would not change it.
if (!getAnchorTag(arg))
return;
document.write(getAnchorTag(arg));
});
function getAnchorTag (name) {
var res = '';
Object.keys(Navigation.Headings).some(function (Heading) {
return Object.keys(Navigation.Headings[Heading]).some(function (Item) {
if (name == Navigation.Headings[Heading][Item].Name) {
res = ("<a href=\""
+ Navigation.Headings[Heading][Item].URL + "\">"
+ Navigation.Headings[Heading][Item].Name + "</a> : ");
return true;
}
});
});
return res;
}
Solution that reduces iterating over the Headings/Items:
var remainingArgs = Args.slice(0);
Object.keys(Navigation.Headings).some(function (Heading) {
return Object.keys(Navigation.Headings[Heading]).some(function (Item) {
var i = remainingArgs.indexOf(Navigation.Headings[Heading][Item].Name);
if (i === -1)
return;
document.write("<a href=\""
+ Navigation.Headings[Heading][Item].URL + "\">"
+ Navigation.Headings[Heading][Item].Name + "</a> : ");
remainingArgs.splice(i, 1);
if (remainingArgs.length === 0)
return true;
}
});
});
How about pushing loops to their end limits
for(var a=0; a<data_a.length; a++){
for(var b=0; b<data_b.length; b++){
for(var c=0; c<data_c.length; c++){
for(var d=0; d<data_d.length; d++){
a = data_a.length;
b = data_b.length;
c = data_b.length;
d = data_d.length;
}
}
}
}
Already mentioned previously by swilliams, but with an example below (Javascript):
// Function wrapping inner for loop
function CriteriaMatch(record, criteria) {
for (var k in criteria) {
if (!(k in record))
return false;
if (record[k] != criteria[k])
return false;
}
return true;
}
// Outer for loop implementing continue if inner for loop returns false
var result = [];
for (var i = 0; i < _table.length; i++) {
var r = _table[i];
if (!CriteriaMatch(r[i], criteria))
continue;
result.add(r);
}
There are many excellent solutions above.
IMO, if your break conditions are exceptions,
you can use try-catch:
try{
for (var i in set1) {
for (var j in set2) {
for (var k in set3) {
throw error;
}
}
}
}catch (error) {
}
Hmmm hi to the 10 years old party ?
Why not put some condition in your for ?
var condition = true
for (var i = 0 ; i < Args.length && condition ; i++) {
for (var j = 0 ; j < Args[i].length && condition ; j++) {
if (Args[i].obj[j] == "[condition]") {
condition = false
}
}
}
Like this you stop when you want
In my case, using Typescript, we can use some() which go through the array and stop when condition is met
So my code become like this :
Args.some((listObj) => {
return listObj.some((obj) => {
return !(obj == "[condition]")
})
})
Like this, the loop stopped right after the condition is met
Reminder : This code run in TypeScript
Assign the values which are in comparison condition
function test(){
for(var i=0;i<10;i++)
{
for(var j=0;j<10;j++)
{
if(somecondition)
{
//code to Break out of both loops here
i=10;
j=10;
}
}
}
//Continue from here
}
An example with for .. of, close to the example further up which checks for the abort condition:
test()
function test() {
var arr = [1, 2, 3,]
var abort = false;
for (var elem of arr) {
console.log(1, elem)
for (var elem2 of arr) {
if (elem2 == 2) abort = true;
if (!abort) {
console.log(2, elem2)
}
}
}
}
Condition 1 - outer loop - will always run
The top voted and accepted answer also works for this kind of for loop.
Result: the inner loop will run once as expected
1 1
2 1
1 2
1 3
XXX.Validation = function() {
var ok = false;
loop:
do {
for (...) {
while (...) {
if (...) {
break loop; // Exist the outermost do-while loop
}
if (...) {
continue; // skips current iteration in the while loop
}
}
}
if (...) {
break loop;
}
if (...) {
break loop;
}
if (...) {
break loop;
}
if (...) {
break loop;
}
ok = true;
break;
} while(true);
CleanupAndCallbackBeforeReturning(ok);
return ok;
};
the best way is -
1) Sort the both array which are used in first and second loop.
2) if item matched then break the inner loop and hold the index value.
3) when start next iteration start inner loop with hold index value.
I need to create a string like this: 01-2--3---4----5-----6------7------- for a let n=7, using a loop.
I've created something like this so far:
let numbers = '';
n = 7;
for(i=0; i<=n; i++) {
numbers += i;
if (i>0) {
numbers += ('-')
}}
which gives me: "01-2-3-4-5-6-7-". Don't know how to change the code so that it could multiply the number of '-' equal n in every loop.
What you need is a nested loop, to iterate over the value of i in the outer loop.
const n = 7
let result=''
for (let i = 0; i <= n; i++) {
let dashes=''
for(let j=0; j < i; j++){
dashes+='-'
}
result+= `${i}${dashes}`
}
console.log(result)
You could use String#repeat for the wanted dash.
Do not forget to declare any variable.
let numbers = '',
n = 7;
for (let i = 0; i <= n; i++) numbers += i + '-'.repeat(i);
console.log(numbers);
This the solution for your problem:
var numbers = '';
var n = 7;
for(var i = 0; i <= n; i++) {
numbers += i;
for(var j = 0; j < i; j++) {
numbers += "-";
}
}
const animal = "cat";
for (let i = 0; i < animal.length; i++) {
console.log(animal[i]);
for (let j = 1; j < 4; j++) {
console.log(j);
}
}
How do I output the answer going straight rather than going down.
Each console.log print in a new line
You can create a variable, assign what you want to display to it then, display it once.
Or
You can use multiple values in one console.log separateb by comma ,
const animal = "cat";
let result = ""
for (let i = 0; i < animal.length; i++) {
result += animal[i]
for (let j = 1; j < 4; j++) {
result += " " + j + " "
console.log(animal[i], j)
}
}
console.log(result)
<script type="text/javascript">
var s = 'First JavaScript string.';
var c = 'This is second text.'
var colors = new Array("#FF0000","#000000");
for (var i = 0; i < s.length; i++)
document.write("<span style=\"color:" + colors[(i % colors.length)] + ";\">" + s[i] + "</span>");
</script>
How do i include 'c' string in the for loop?
You don't need to put single statements in the for loop, you can have how ever many as you want, as long as the centre expression evaluates to a truthy value:
Some examples:
Multiple declarations and a bigger condition:
for(var i = 0, z = 0; i < 100 && z < 100; z++, i++){
console.log(i, z)
}
No incrementation and no declaration:
var i = 0;
for(;i < 100;){
i++;
console.log(i)
}
For your situation I think you want this:
for (var i = 0; i < s.length && i < c.length; i++){
//...do something here
}
This will stop when I is bigger then the length of s or the length of c
If I understand correctly you need to use a nested loop, although you need to be more specific.
<script type="text/javascript">
var s = 'First JavaScript string.';
var c = 'This is second text.'
var colors = new Array("#FF0000","#000000");
for (var i = 0; i < s.length; i++) {
for (var m = 0; m < c.length; m++) {
... print something in here
}
}
</script>
for (var i = 0, var j = 0; i < s.length; i++, j--) {
;
}
Condition should be false, when i is greater/equal to summarized length of s and c.
If i is smaller than length of s, you should write s[i] (with marking), else - write c[i-s.length]. I'd say that ternary operator would fit great here.
I'm trying to display all the prime numbers up to 10 and it isn't working. Can you see what I did wrong?
function findPrimeNumbers() {
var count = 10,
primes = [];
for (var i = 0; i <= count; i++) {
if (count / i === 1 || count) primes.push(i);
else continue;
count -= 1;
}
for (var i = 0, len = primes.length; i < len; i++) return primes[i];
}
console.log(findPrimeNumbers());
It only returns 0 in the console.
Here's about the simplest way to generate primes. Note that there are more efficient methods, but they are harder to understand.
function findPrimeNumbers (count) {
var primes = [];
for (var J = 2; J <= count; J++) {
var possPrime = true;
for (var K = 2, factorLim = Math.sqrt (J); K <= factorLim; K++) {
if (J % K == 0) {
possPrime = false;
break;
}
}
if (possPrime)
primes.push (J);
}
return primes;
}
console.log (findPrimeNumbers (10) );
This yields all the primes <= 10:
[2, 3, 5, 7]
See Wikipedia for an explanation.
for (var i = 0, len = primes.length; i < len; i++) return primes[i];
Here you are return just the first element of the array. I think you meant something like this
var retstr = "";
for (var i = 0, len = primes.length; i < len; i++)
{
//To improve str format
if(i == len-1)
retstr += primes[i];
else
retstr += primes[i] + ", ";
}
return retstr;
Hope this helps.
if (count / i === 1 || count / i === count)
You don't say how it's not working, but the first thing that comes to my attention is that you're incrementing i, while at the same time decrementing count, so i will never get all the way to 10.
Also, count / i will cause a divide-by-zero error on the first iteration as it's written (unless Javascript magically handles that case in some way I'm not familiar with).
Then you "loop" through your return values--but you can only return once from a function, so of course you're only going to return the first value.
And you are returning from the function in the last for loop. Remove that for loop, just return the array.
function PrimeCheck(n){ //function to check prime number
for(i=2;i<n;i++){
if(n%i==0){
return false
}
}
return true;
}
function print(x){ //function to print prime numbers
var primeArray=[];
for(j=2;j<x;j++){
if(PrimeCheck(j)==true){
primeArray.push(j);
}
}
console.log(primeArray);
}
print(10); //[2,3,5,7]