I want to improve my code

So I have finished this exercise, but I would like to improve my code but I have no idea what to do.

``````// Write your code below
const tinasFollowers = ['John', 'Max', 'Moon'];
let mutualFollowers = [];
for ( let b = 0; b < bobsFollowers.length; b++){
for (let t = 0; t < tinasFollowers.length; t++){
if (bobsFollowers [b] === tinasFollowers [t]){
mutualFollowers.push (bobsFollowers[b]);
}
}
console.log (mutualFollowers);
}
``````

The outcome of this code will be
[ ‘Max’ ]
[ ‘Max’, ‘Moon’ ]
[ ‘Max’, ‘Moon’ ]
[ ‘Max’, ‘Moon’ ]
I completely understand what is happening inside the for loop and give me this outcome.
But what if I want the answer become
[ ‘Max’, ‘Moon’ ]only?
How can I “hide” the incomplete/repetitive outcome, or writing it in another way (which maybe I haven’t learn since I am complete rookie of coding), I am very curious for the answers

Consider where your log statement is. What happens if you place it in different spots instead?

I have changed to different position but seems like the best output is
[ ‘Max’ ]
[ ‘Max’, ‘Moon’ ] ,

I cannot make it to [ ‘Max’, ‘Moon’ ] only since the for loop will always touch the

``````const bobsFollowers = ['Max','Moon','Joe','Adam'];

``````

first before anything else

What if you put it after all the brackets?

OMG it worked, can you explain a little bit more

I think its about the way that how JS store data?

I want to learn more since I am not a CS student, I am lacking of fundamentals.

It’s really about the nature of the for-loop and the bracket system. Anything that falls under the brackets inside of a for-loop will be repeated as many times as the for-loop runs.

1 Like