JavaScript - For loops inside of for loops - Output Query?


#1

https://www.codecademy.com/courses/learn-javascript/lessons/loops/exercises/for-loops-iii?action=lesson_resume

In the JavaScript exercise 5, I have created the following code which is getting the tick as correct - but isn't the point of the exercise to find and display ONLY the match? The output I get is:

Paris
Rome
Chicago
Paris
Match: Paris
New York
Rome
Chicago
Paris
Barcelona
Rome
Chicago
Paris

My code is:


var myPlaces = ['Greece', 'Durban', 'Canada'];
var friendPlaces = ['London', 'Durban', 'Zambia'];

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(myPlaces[i]);
     }
   }
}


#2

here:

for (var i = 0; i < myPlaces.length; i++){
	console.log(myPlaces[i]);
  
   for (var j=0; j < friendPlaces.length; j++){
     console.log(friendPlaces[j]);

the console.logs on this lines will causes to log everything

you should only have 1 console.log in your if clause if you want to achieve what you want to achieve


#3

as already mentioned by @stetim94 .
In doubt You can also look at this thread..


#4

Got! Thanks guys! Dunno why I didn't assume those 2 console.log lines wouldn't push everything in the loop out Adjusted the code to get what i wanted:

var myPlaces = ['Greece', 'Durban', 'Canada'];
var friendPlaces = ['London', 'Durban', 'Zambia'];

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]);
     }
   }
}

#5

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