FAQ: Loops - Nested Loops


#1

This community-built FAQ covers the “Nested Loops” exercise from the lesson “Loops”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Introduction To JavaScript

FAQs on the exercise Nested Loops

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!


#2

2 posts were split to a new topic: Giving me an error


#4

2 posts were merged into an existing topic: Giving me an error


#5

Struggling to print this to the console as a String - it only prints numbers (1 and 2). Im not sure what I am doing wrong, any ideas? code below

const bobsFollowers = [‘john’, ‘sam’, ‘chris’,‘pen’]
const tinasFollowers = [‘john’, ‘michelle’, ‘sam’]
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(i))
}
}
}


#6

First of all, with mutualFollowers.push(i), you are pushing a number from the for loop into the empty array, not the actual value of one of the arrays. So it either needs to be mutualFollowers.push(tinasFollowers[j]) or mutualFollowers.push(bobsFollowers[i])

Next, if you console.log the push, you are actually returning the output of the .push method, which will always return the LENGTH of the array you are pushing into.

JavaScript Array push() Method
Return Value: A Number, representing the new length of the array

So when the nested loop gets a match, it will push the number (or the name, that doesn’t matter) in the array, and it will return the length of the array, which is now 1. Then it happens again at the second match and it will return the length 2.

var animals = ['pigs', 'goats', 'sheep'];

console.log(animals.push('cows'));
// expected output: 4

#9

7 posts were split to a new topic: Nested loops


#10

I just wanted a bit of confirmation. I have the correct code but just wanted to clarify something that didn’t make sense to me.

If I run the loop for either bobsFollowers or tinasFollowers the output is the number of items are in the array (i.e 4). But running the nested loop compares the names and produces the names that match.

I suppose what I’m asking is why isn’t it comparing number of items or lengths?

My code below:

// Write your code below
const bobsFollowers = ['Tasha','Jane','Mark','Steven'];
const tinasFollowers = ['Tasha','Ryan','Jane'];

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(tinasFollowers[j]);
    }
  }
};

console.log(mutualFollowers);
//output:  [ 'Tasha', 'Jane' ]

#11

Because that is trivial information. All we want is the matches.


#12

Is there a way to get the value of the index and use that string in the output? So this is my code:

let bobsFollowers = ['Linda', 'Gene', 'Tina', 'Teddy'];
let tinasFollowers = ['Jimmy Jr.', 'Linda', 'Gene'];
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('Both are friends with: ' + mutualFollowers.push(bobsFollowers[i]))
    }
  }
}

It works, but prints
Both are friends with: 1
Both are friends with: 2

I’ve tried searching around different websites but haven’t found anything that prints out their names instead yet. It’s not something I desperately need to solve, but I’m curious.


#13

This expression is concatenating a string value but that value is the return from the push method, which is the new length of the array, hence, a number.


#14

I had the same issue as a number of the others. I was expecting to see the mutual strings in my output:

// Write your code below

const bobsFollowers = ['Jenni', 'Dave', 'Greg', 'Valerie'];
const tinasFollowers = ['Heather', 'Jenni', 'Dave'];

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.push(tinasFollowers[j]));
    }
  }
}
console.log(mutualFollowers);

And then it occurred to log the new array on its own and it printed the names for me, which also gave me the mutuals plus and ‘undefined’ result that needed an additional tweak in the loop to get rid of.

Does this constitute the correct approach?


#15

This is combining two operations in one. Is it necessary to log while looping?


#16

No, I suppose not. I could just drop the first console.log part inside the loop and as long as I keep the act of pushing to the mutualFollowers array in there.

Because like I had it, the output was:

1
2
[ ‘Jenni’, ‘Dave’ ]

But if I just cut out the logging part inside the loop, I get just the mutual array contents without the counting data:

[ ‘Jenni’, ‘Dave’ ]


#17

(Which I guess makes more sense).


#18

Apologize if this has been answered already (I didn’t see the question asked yet)

why does this work?

const bobsFollowers = ['Jim', 'Joe', 'Jerry', 'John'];
const tinasFollowers =['Jessica','Jim', 'Joe'];
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)

It seems to me that the array would never match the names as the indexes are off by 1 (Jim is index 0 in bob’s array and index 1 in tina’s) When index 0 for bob’s array is called, it gets Jim, when index 0 is called for tina’s, it gets Jessica… How would these ever equal each other? Very likely I misunderstanding some concept…

thanks in advance.


#19

the loops are nested, so for each friend of bob, we loop over all the friends of tina.

first friend of bob, loop over all friends of tina, and compare each friend of tina with first friend of bob
second friend of bob, loop over all friends of tina, and compare each friend of tina with second friend of bob
etc etc.

we can see this if you like:

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

#20

Ah i see it now… Thanks!


#21

Hi. I’m a little stuck. I’m working on Nested Loops. I want to separate the loop and the part that checks for matches, so i’ve put them in functions.

Separately, they run fine. But, I can’t figure out how to pass the values back and forth between functions. Here’s the code below , commented as best i can to clarify my thought process. Any help appreciated, thanks.

// Our array variables for later use. 
let bobsFollowers = ['p1', 'p2', 'p3', 'p4'];
let tinasFollowers = ['p1', 'p2', 'tinaspal'];
let mutualFollowers = [];

//Iterates through each index of each array. 
const loopTheArrays = (arr1, arr2) => {
  for (let i = 0 ; i < arr1.length ; i++) {
  for (let j = 0 ; j < arr2.length ; j++) {
    
  }
} };

/* 
Entered to ensure no infinite loop when executing.  Seems to be okay:   
loopTheArrays(bobsFollowers, tinasFollowers); */

// Function to compare array indexes.  
const compareIndexes = (arrayOneIndex, arrayTwoIndex) => {
  if(arrayOneIndex === arrayTwoIndex) {
    mutualFollowers.push(arrayOneIndex);
    	// Is there a way to pass the info from this 					function to the loop, to continue after 				it finds a match and pushes it to mutual 					followers?
  }
};

/* The function calls below are probably wrong. 
I'm trying to run the if loop on each iteration.  So it should loop once, pass to comparison function, check and push if a match, then call the loop function again to continue.  */

compareIndexes(loopTheArrays(bobsFollowers, tinasFollowers));
console.log(mutualFollowers);

#22

That just adds to the code bloat, in this instance. Putting the comparison right in the loop and pushing to the array on matches is much more clear to the reader.

There is nothing to pass since you are pushing to the array. The global object is the result when the function is complete.

Sometimes we don’t want a global object that is manipulated by our function, but rather have our function create, popuplate and return an object.

const find_mutual_followers = (m, n) => {
  result = []
  for (a in m) {
    for (b in n) {
      if (a === b) {       // This is much to simple to
        result.push(a);    // justify creating a function
      }
    }
    return result;
};

const mutual_followers = find_mutual_followers(bobsFollowers, tinasFollowers)

For the sport of it, let’s try to do what your above code is attempting…

const sameAs = (a, b) => a === b;

const find_mutual_followers = (m, n) => {
  result = []
  for (a in m) {
    for (b in n) {
      if sameAs(a, b) {
        result.push(a);
      }
    }
    return result;
}

const mutual_followers = find_mutual_followers(bobsFollowers, tinasFollowers)

#23

Hey MTF, thanks for your time.

So two take-aways from this:

  1. What I’m trying is essentially unnecessary in this case, possibly convoluted.

  2. Looking at your effort to do what the code intended, it’s probably a little outwith my ability atm too?

I’ll refactor the code so it’s inline with what the lesson wants again. This was more of a tangent haha.