What happens if my arrays aren't the same length?

What’s the reason that my array at the end of this has an undefined entry?

// Write your code below
let bobsFollowers = ['a','b','c','d'];
let tinasFollowers = ['a','b','e'];
let mutualFollowers = [];

for (let i=0; i<=bobsFollowers.length; i++) {
  for (let j = 0; j<=tinasFollowers.length; j++) {
    if (bobsFollowers[i]===tinasFollowers[j]) {
      //console.log(mutualFollowers.length);
      mutualFollowers.push(tinasFollowers[j]);
      console.log(mutualFollowers);
    }
  }
};

My results are:

[ 'a' ]
[ 'a', 'b' ]
[ 'a', 'b', undefined ]
1 Like

It likely has to do with the one list being longer than the other. What happens if you push bobsFollowers[i]?

I get the following result:

[ 'a', 'b', 'd' ]

:thinking:

Consider the conditionals in your for loops. Is there any reason to write <=?

2 Likes

Of course it’s an off by 1 error! :persevere:
Thank you! I’ve got it working and understand now.

2 Likes

You call : mutualFollowers.push(tinasFollowers[j]); instead mutualFollowers.push(bobsFollowers[j])
you got the last undefined because you have ‘’<=’’ in tinasFollowers. this <= including ‘‘d’’ element
try this way:

let bobsFollowers = [‘a’,‘b’,‘c’,‘d’];
let tinasFollowers = [‘a’,‘b’,‘e’];
let mutualFollowers = ;

for (let i=0; i<=bobsFollowers.length; i++) {
for (let j = 0; j<=tinasFollowers.length; j++) {
if (bobsFollowers[i]===tinasFollowers[j]) {
//console.log(mutualFollowers.length);
mutualFollowers.push(bobsFollowers[j]);
}
}
};
console.log(mutualFollowers);