Comparison: the common match


#1

<PLEASE USE THIS TEMPLATE TO HELP YOU CREATE A GREAT POST!>

Here the exact link to the exercise:
https://www.codecademy.com/fr/courses/learn-javascript/lessons/loops/exercises/for-loops-iii?action=lesson_resume

My code looks good since I can move forward but the comparison didn’t work since it is said: undefined.


When I run it: ( Mongolia should be the output )

Mongolia
Japan
China
Mongolia
Island
New Zealand
Match: undefined



the code:
var myPlaces = ['Mongolia','Japan','China'] ;
var friendPlaces = ['Mongolia','Island','New Zealand'];
for( var i = 0; i < myPlaces.length; i++) {
  console.log(myPlaces[i]);
}
  for(var j = 0; j < friendPlaces.length; j++) {
    console.log(friendPlaces[j]);
  }
    if (myPlaces[i] === friendPlaces[j]) {
      console.log('Match: '+ myPlaces[i]);
    }



#2

Hi @lowla,

You get undefined because the IF statement, myPlaces[i] === friendPlaces[j], the i and j cannot access to the counter for the two loops you’ve created, because it is created outside of the running loops.


You need to nest your IF statement inside the second FOR loop, then both of them being nested inside the first FOR loop.

Your code:

for (.... ) {
   .....
}   //<== closes the first FOR loop
   for (... ) {
      ......
   }  //<== closes the second FOR loop
      if (.....) {
         .....
       } //<== closes the IF statement

//There is no nesting involved

Whereas it should be:

for (......) {
   ........
   for (......) {
   ........
      if (.....) {
      ......
      } //<== closes the IF statement
   } //<== closes the second FOR loop
} //<== closes the first FOR loop

Hope it helps :slight_smile:


#3

Thanks it did actually. I even improve my code : I noticed I’ve been printed the list of myPlaces and friendPlaces when actually I didn’t really needed that, I just needed the output Match: ’ the common place ’

so here is the bette version :


var myPlaces = [‘Mongolia’,‘Japan’,‘China’];
var friendPlaces = [‘Mongolia’,‘Island’,‘New Zealand’];
for( var i = 0; i < myPlaces.length; i++) {
for(var j = 0; j < friendPlaces.length; j++)
if (myPlaces[i] === friendPlaces[j]) {
console.log('Match: '+ myPlaces[i]);
}}



#4

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