2

when sameFriends = [];

'dick', 'rex', 'james' gets push in

when I added 'golf', //output remove james

How can I add push in the same element from aFriend and bFriend without removing any?

let aFriend = ['dick', 'rex', 'james', 'tom', 'jack'];
let bFriend = ['dick', 'rex', 'james', 'jake'];
let sameFriend = ['golf'];

for (let i = 0; i < aFriend.length; i++){
  for (let k = 0; k < bFriend.length; k++){
    if (aFriend[i] === bFriend[k]){
      sameFriend.push(bFriend[k]);
      console.log(sameFriend[k]);
    }
  }
}
3
  • 1
    Your code although can be bettered but works correctly. I see this output : ["golf","dick","rex","James"]. What do you expect? Commented Jun 25, 2021 at 9:44
  • 1
    console.log(sameFriend[k]); The index k is for array bFriend not sameFriend witch is not the same size... Commented Jun 25, 2021 at 9:48
  • You can do this with one line : console.log(sameFriend.concat(aFriend.filter(item => bFriend.indexOf(item) >= 0))); Commented Jun 25, 2021 at 9:53

2 Answers 2

1

You can use code as below:

let aFriend = ['dick', 'rex', 'james', 'tom', 'jack'];
let bFriend = ['dick', 'rex', 'james', 'jake'];
let sameFriend = ['golf'];

for (let i = 0; i < aFriend.length; i++){
    for (let k = 0; k < bFriend.length; k++){
        if (aFriend[i] === bFriend[k]){
        sameFriend.push(bFriend[k]); //Here sameFriend array will have all elements which are same
       // console.log(sameFriend);
        }
    }
}
console.log(sameFriend);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @FZs just reread the details and updated code to reflect the desired output.
1

Method 1: Change

console.log(sameFriend[k]);

To

console.log(bFriend[k]);

and add

console.log(sameFriend); 

before entering 'for loop'.

The element you push into sameFriend is not stored at kth index of it. That is why James didn't get printed.

Method 2:

Remove the console statement inside the 'for loop' and add

console.log(sameFriend);

at the end of the code to print all elements of sameFriend

2 Comments

I want it to print the similar names in aFriend and bFriends and including the element in sameFriend. That's why I'm using .push()
Either You can print the elements of sameFriend before 'for loop' and then proceed with 'for loop' with change I have mentioned OR add "console.log(sameFriend)" at the end of the code and remove console statement inside the 'for loop'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.