Running One For Loop Inside of Another - Placement of Match Statement


#1


How do I get the log to print out the matching statement at the end, instead of after the section which contains a match?


var myPlaces = ["Toyko", "Seoul", "Barcelona"];
var friendPlaces = ["Iceland", "Bhudan", "Seoul"];

for(i = 0; i < 3; i++) {
    console.log(myPlaces[i]);

    
for(j = 0; j < 3; j++) {
    console.log(friendPlaces[j]);

if(myPlaces[i] === friendPlaces[j]) {
    console.log("Your friend and you both want to visit " + myPlaces[i] + "!")
}
}
}


#2

you could do something like:

var myPlaces = ["Toyko", "Seoul", "Barcelona"];
var friendPlaces = ["Iceland", "Bhudan", "Seoul"];
var bothPlaces = []

and then if there is a match:

if(myPlaces[i] === friendPlaces[j]) {
   bothPlaces.push(i);
}

then at the end of your code, print the items in bothPlaces array


#3

Got called away while I was writing this, so it comes an hour later than when started. Here it is, anyway...

var myPlaces = ["Toyko", "Seoul", "Barcelona"];
var friendPlaces = ["Seoul", "Iceland", "Bhudan"];

To the above variable declarations, let's add a default message string.

var i, j, f = false, msg = "No match found.";

Now run through the loops without logging anything.

for (i = 0; i < myPlaces.length; i++) {
    for (j = 0; j < friendPlaces.length; j++) {
        if (myPlaces[i] === friendPlaces[j]) {
            msg = "Your friend and you both want to visit " + myPlaces[i] + "!";
            f = true;
            break;
        }
    }
    if (f) break;
}

console.log(msg);

 > i
=> 1
 > j
=> 0

#4

haha, mtf, I like that you've taken this to the next level, but this is way beyond where I'm at right now. I wish I could understand this, but you've lost me starting with the line, var i, j, f = false, msg = "No match found.";. I can pick up what you're doing again in the next section:

for (i = 0; i < myPlaces.length; i++) {
for (j = 0; j < friendPlaces.length; j++) {
if (myPlaces[i] === friendPlaces[j]) {
msg = "Your friend and you both want to visit " + myPlaces[i] + "!";

then you lose me again here:

f = true;
break;
}
}
if (f) break;
}

console.log(msg);


#5

Also, what does this do??

i
=> 1
j
=> 0


#6

I'll answer this one first. It's the console command line output from when the code had just been run. The match was found when i was 0 and j was 1.


#7

We could have used four lines, instead. But var takes a list. No harm in giving it one. Now we know that all four variables are scoped alike.

It also means that i and j no longer have block scope in their loop blocks. Those variables are visible outside of the blocks in a stricter environment such as ES6, 2015, 2016 or whatever the latest flavor is.


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.