0

I have

arr1 = [aaa,bbb,ccc,ttt,yyy]
arr2 = [abc,ttt,def,hij,ew,y,uuu]

I want the same/common items in both arrays to be saved in a new array

Same_items = [ttt]

I have tried using

var Same_items = [];
  for(let i = 0; i < arr1.length; i++) {
    if(arr2.indexOf(arr1[i]) !== -1) {
      Same_items.push(arr1[i]);
    }
  }

also,

var Same_itema = [];
Same_items = arr1.filter(item => arr2.includes(item));

I not getting the desired output. I am not doing it right. Please guide

Thank you!

2
  • 2
    I think that if const arr1 = ["aaa", "bbb", "ccc", "ttt", "yyy"]; and const arr2 = ["abc", "ttt", "def", "hij", "ew", "y", "uuu"]; are the sample input values, Same_items of Same_items = arr1.filter(item => arr2.includes(item)); will return the value of ["ttt"]. So, can you provide the detail of I not getting the desired output.? For example, how about console.log(["aaa", "bbb", "ccc", "ttt", "yyy"].filter(item => ["abc", "ttt", "def", "hij", "ew", "y", "uuu"].includes(item)))? Also, I think that your above script returns ["ttt"]. Commented Jan 10, 2023 at 11:41
  • 2
    I am sorry, I missed to check the output closely. Thank you @Tanaike- san Commented Jan 10, 2023 at 12:30

1 Answer 1

1

I'm writing this answer as a community wiki since the solution was provided by @Tanaike-san and the OP (@Alicia Stone) in the comments section.

Both options:

  const arr1 = ["aaa", "bbb", "ccc", "ttt", "yyy"];
  const arr2 = ["abc", "ttt", "def", "hij", "ew", "y", "uuu"];

  Same_items = arr1.filter(item => arr2.includes(item));

  Logger.log(Same_items)

and

  const arr1 = ["aaa", "bbb", "ccc", "ttt", "yyy"];
  const arr2 = ["abc", "ttt", "def", "hij", "ew", "y", "uuu"];

  console.log("second option: " + arr1.filter(item => arr2.includes(item)))

will return the same/common items in both arrays.

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

Comments

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.