FAQ: Loops - Nested Loops

Since the values match, it won’t matter which one is assigned.

a = arrayA[k]
b = arrayB[j]

if (a === b) {
    c.push(a)
}

same as, c.push(b).

1 Like

Midlindner, thanks for your helpful response. I think that’s some cool code but the course is not that advanced to show us all of that yet, let alone it’s interaction with for loops, nested loops etc. Looking at the above makes me realise how much I haven’t yet learned and my head is in spaghetti with the code from the exercise already. For example, putting the countI++ and countJ++ on the end of the for loops increments them by 1, but why is that necessary? The answers of stetim94 and ionatan are a little glib and not very helpful either. Don’t make an assumption that we’re all at the same knowledge level please. If you’ve nothing helpful to say, nothing is better than something snarky.

I’m finding more and more that Codecademy is about learn this and move on, not the ‘why and how it works’. I still haven’t a clue how a for loop differs from a while…do, because every exercise is one single example for something that undoubtedly needs a few examples to explain well and is highly abstract for newcomers. I have similar questions to ‘treswm’ and find that the course doesn’t exactly help me to work it out well. Coding is about understanding at a deep level so that your brain begins to look for solutions to complex challenges from a base of JS logic, not just throw this code at the wall and see if it sticks. You people here on the forums are that part (the real explanation), and not the exercises themselves and I detect a little frustration from some seasoned veterans who don’t know why beginners can’t put a complex bunch of logging code together when they’re already struggling with the basics.

Really nice simplified explanation of a loop and way better than “initialisation, iteration (when has anyone used that word!), stopping condition”.

But isn’t is more

for ( start; stop; step ) 

Example:

for (A = 0; A < variable.length; A++)
     start;  stop;         step  

I tend to agree with that assessment. Keep in mind, that once you’ve completed an exercise, you can experiment with the code to gain a deeper understanding. Good programmers are also good researchers. Google, Stack Overflow, the official documentation for the language, forums like this one are all helpful to gain knowledge and get ideas for how to solve coding problems.

Since you mentioned loops, consider the following. If you feel like it’s over your head right now, no worries. Come back to it later. While loops and for loops are essentially the same thing. Any loop is really just telling the computer to do something over and over until the stop condition is met.

// The expressions in a for statement are actually optional // Not saying you should do this, but it may help // with understanding how loops work. let i = 1; for(;;){ console.log(`${i} Mississippi`); i++; if(i > 5) { break; } } console.log(''); // Print a blank line // The above is the same as this (much shorter) for(let i = 1; i <= 5; i++) { console.log(`${i} Mississippi`) } console.log(''); // This is also the same thing let j = 1; while(j <= 5) { console.log(`${j} Mississippi`); j++; }

If you’d really like to dig into loops, read through the documentation. :slightly_smiling_face:

My console log output looks right, but I can’t figure out why codeacademy won’t accept:

// Write your code below
const bobsFollowers = [‘joe’, ‘kathy’, ‘terry’, ‘bongo’];
const tinasFollowers = [‘points’, ‘terry’, ‘joe’];
const 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.push(’ + bobsFollowers[i]+ ‘)’);
mutualFollowers.push(bobsFollowers[i]);
}
}
}

keeps giving me:

Did you include a nested for -loop in your code? Ensure: - You use let or var for iterator variables in your loops. - For example: let i = 0 , instead of i = 0 - bobsFollowers is in the outer loop - tinasFollowers is in the inner loop. - You append elements to mutualFollowers in the inner loop

Your function shouldn’t be logging anything, except to test it. Remove that line so the SCT doesn’t see it.

Thanks I did remove it. I’d only added that in there to see if my push statement was correct…

I found the ‘get unstuck’ feature that diffed my version to the solution. Says that it wanted my arrays to be defined with let instead of const. That doesn’t seem super clear in the exercise, but changing it got me through.

Thanks for the response

1 Like

I take it back. Still doesn’t work. Weird.

// Write your code below
let bobsFollowers = [‘joe’, ‘kathy’, ‘terry’, ‘bongo’];
let tinasFollowers = [‘points’, ‘terry’, ‘joe’];
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]);
}
}
}

Got it. Didn’t like the spaces before the let term in the for loops…

1 Like

I get undefined in output. I don’t why.

const bobsFollowers = [‘num1’, ‘num2’, ‘num3’, ‘num4’];
const tinasFollowers = [‘tina1’, ‘num1’, ‘num4’];
const 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);

Output:
[ ‘num1’, ‘num4’, undefined ]
Why undefined??

Since you are iterating up to and including __Followers, you are getting a match on the non-existent element.

x <= array.length

will attempt to access the first non-existent element of the array.

x < array.length

will end when the last existing element is reached.

1 Like

Thanks a lot for taking your time to explain!

1 Like

why can’t I .push(tinasFollowers) instead ?

That would push the whole array?

But given you have determined that bobsFollowers[i] and tinasFollowers[j] are equal, you could use either

So I tried to figure this out but it told me that my initial code was wrong.
I used this,

const bobsFollowers = ['Mike', 'Jill', 'Rich', 'Fred'];
const tinasFollowers = ['Mike', 'Fred', 'Sue'];
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(tinasFollowers[j]);
      console.log(mutualFollowers);
    }
  }
};

It printed to the console,

[ 'Mike' ]
[ 'Mike', 'Fred' ]

The program said that it was wrong.
So, I thought about it, tried some different things, and ended up lookin at the solution, to which I added a console.log to,

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

and it printed

[ 'Marta' ]
[ 'Marta', 'Sam' ]

So, why was mine wrong, and the example right?

I’m sure I made some mistake, but I cannot figure out what.

Thank you!

Looks like your code is functionally the same as the solution. It simply pushes the element from tinasFollowers to the mutualFollowers array, rather than the element from bobsFollowers. It might just be a case where the requirements to pass were very strict and specific; your code works just fine.

1 Like

Thanks for your review and the info!

1 Like

For the lesson here I’m confused on why my answer is wrong? Even after viewing the solution (I know I know) but I only viewed it as I was pretty confident my answer was right.

And after viewing the solution the only difference in the solution was my names in the array so not sure why it didn’t accept my answer…

let bobsFollowers = ['Matt', 'Jake', 'Kaylee', 'Grace'];
let tinasFollowers = ['Grace', 'Kaylee', 'Arthur'];

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

What am I missing here?

Apparently that extra space in the array was causing the error?

Changing the code below fixed it.

let mutualFollowers = []

why do nested for loops compare arrays I don’t understand how does that work exactly, I can replicate the same for loops to compare two arrays but I don’t understand why it works.
I hope someone explain or give an article or a video that explains how nested loops work exactly.
Thanks you in advance.