Doubts in nested loops exercise


#1

Good afternoon everyone,
I was trying to learn about nested loop , and in one excersice i get stuck and ask for the solution, the problem it’s that i’m not agreed with the solution. I’m new here but i found this could be a interesting way to understand my mistake.
This was the exercise:

Create a nested loop that iterates through bobsFollowers as the array for the outer loop, and tinasFollowers as the array for the inner array. If the current element from the outer loop is the same as the current element from the inner loop, push the that element into the mutualFollowers array.

So the steps before ask two create three variables, and them put in the mutualFollowers the name’s that are in both lists. This was the automatic resolution:

let bobsFollowers = ['Joe', 'Marta', 'Sam', 'Erin'];
let tinasFollowers = ['Sam', 'Marta', 'Elle'];
let mutualFollowers = [];

for (let i = 0; i < bobsFollowers.length; i++) {
  for (let j = 0; j < tinasFollowers.length; j++) {
    if (bobsFollowers[i] === tinasFollowers[j]) {
      mutualFollowers.push(bobsFollowers[i]);
  console.log(mutualFollowers);
    }
  }
};
// the output was 
[ 'Marta' ]
[ 'Marta', 'Sam' ] 

What i did, and the exercise wasn’t correct was:

const bobsFollowers = ['Joe', 'Marta', 'Sam', 'Erin'];
const tinasFollowers = ['Sam', 'Marta', 'Elle'];
let mutualFollowers = ['  '];

for (let i = 0; i < bobsFollowers.length; i++) {
  for (let j = 0; j < tinasFollowers.length; j++) {
    if (bobsFollowers[i] === tinasFollowers[j]) {

      mutualFollowers = (bobsFollowers[i]);
  console.log(mutualFollowers);
    }
  }
};

// outuput :
Marta
Sam

and my answer wasn’t accept. So i don’t understand why, can you help me?
link:https://www.codecademy.com/courses/introduction-to-javascript/lessons/loops/exercises/for-loops-iii?action=resume_content_item


#2

Please post a link to the exercise so we can test your code.


#3

https://www.codecademy.com/courses/introduction-to-javascript/lessons/loops/exercises/for-loops-iii?action=resume_content_item thank you.


#4

Was that link already there in the opening post? If so, my bad for not spotting it.

An empty list is, [], with no content, not even an empty string.

Your function should be logging the list. I’m not a big fan of printing inside a loop (intermediate results) and would rather just construct the list in the loop, and log it outside of (after) the loop.

mutualFollowers = (bobsFollowers[i]);

should be,

mutualFollowers.push(bobsFollowers[i]);

#5

I think your code wasn’t wrong if it logged Marta and sam to the console, and I don’t see any problems with your code. I think it’s because how codecademy testes files. It needs to be the same even if yours work


#6

Nothing of the sort. The expected result is an array with two names in it. The OP code should not pass since it does not do that.


#7

OK thanks. Good to know :grinning: