Home > database >  Check two arrays in google apps script and save common items in a new array
Check two arrays in google apps script and save common items in a new array

Time:01-12

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!

CodePudding user response:

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.

  • Related