Vacation compare - I don't understand the result


#1

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

My code Behave correctly I guess but I don't understand the result. I should have my destinations printed first then my friend's destination then our common destination no ?


var myPlaces = [1, 2, 3];
var friendPlaces = [1, 2, 3];

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


#3

I've got this result instead :
1
1
Match: 1
2
3
2
1
2
Match: 2
3
3
1
2
3
Match: 3


#4

no, it will print your first destination, then all your friends destination + match

then it will print your second destination, then all your friends destination + match

same for your third destination

because the loop which loops over your friends places is nested inside the loop which loops over your places, it log all your friends places for each place you visited

This allows us to find a match


#5

At first, first loop runs, then the loop inside it runs, then if-clause runs on matching condition,so its looks mixed up,use this tool to visualize your code.


#6

But on the first line it's only printing '11' it's not my first destination, then all my friends destination + match


#7

// first itertion of myPlaces loop
1 // console.log(myPlaces[i]);
1 // console.log(friendPlaces[j]);
Match: 1 // console.log('Match: ' + myPlaces[i]);
2 // console.log(friendPlaces[j]);
3 // console.log(friendPlaces[j]);
// second iteration of myPlaces loop
2 // console.log(myPlaces[i]);
1 // console.log(friendPlaces[j]);
2 // console.log(friendPlaces[j]);
Match: 2  // console.log('Match: ' + myPlaces[i]);
3 // console.log(friendPlaces[j]);
// final iteration of myPlaces loop
3 // console.log(myPlaces[i]);
1 // console.log(friendPlaces[j]);
2 // console.log(friendPlaces[j]);
3 // console.log(friendPlaces[j]);
Match: 3 // console.log('Match: ' + myPlaces[i]);

i matched the output with the console.log statements that cause the output. You don't have 11 anywhere?

each run of of the myPlaces loop will cause the whole friendPlaces loop to run again


#8

ok, Now I get it, thank you so much for your help !


#9

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