I have a nested Loop to compare two array indexes and log the equals indexes and non equal indexes but it make the indexes repeated

let bobsFollowers=['Ahmed','Mahmuod','ali','hussam'];

let tinasFollowers  = ['Ahmed','Ali','hussam'];

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('There is mutual Friends :'





 else if (bobsFollowers[i] !== tinasFollowers[j]){

   console.log('the Non Mutual Freinds are  ' +bobsFollowers[i]+' '+ tinasFollowers[j]);



   console.log('There are All Mutual')





I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

Hi @mahmuodaboalhassan, welcome to the forum.

Can you please elaborate what is that you are trying to accomplish?
I don’t understand the ultimate goal.

Also what exactly do you mean by “makes the indexes repeat”?
Are you referring to console.log?

Finally, a word of advice: your code works based on index, is that desired?
For example let’s imagine two lists that have a common element but at a different position, what is your desired output?

let a = ["apple", "banana"];
let b = ["pear", "orange", "plum", "apple"]

// should "apple" be in the common result?


Welcome to the forum.

First, you don’t need two nested loop for this.
You can do it with one loop,

  1. loop it
  2. check if the element in the first array exist in the second array (you can either use array method like includes or indexOf)

the first Array have looped in the second arry three times Right ? , then it take’s the first value that make true . but the twice values that are also true go to the un-mutual

else if (bobsFollowers[i] !== tinasFollowers[j]){

   console.log('the Non Mutual Freinds are  ' +bobsFollowers[i]+' '+ tinasFollowers[j])

That’s a nested loop, you should probably review how they works, but pretty much
for each element of the first array, you are iterating over each element of the second.

Or in practice:

i= 0;
j= 0 / j = 1 / j = 2;

So you will have

"Ahmed" === "Ahmed"
"Ahmed" === "Ali"
"Ahmed" === "hussam"

Is it clearer now? :sparkles:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.