-1

I have two arrays

array1 = ["ab", "xyz", "qr", "pqrs"]
array2 = ["ab", "def", "lmno", "def", "qr", "pqrs"]

how to compare these two arrays and get a third array of the element from first array which is not found in second array.

Desired result:

unique = ["xyz"]

Thanks in advance

zachi
  • 374
  • 2
  • 3
  • 12

2 Answers2

2

Possible solution using Array#filter.

var array1 = ["ab", "xyz", "qr", "pqrs"],
    array2 = ["ab", "def", "lmno", "def", "qr", "pqrs"],
    unique = array1.filter(v => array2.indexOf(v) == -1);
    
    console.log(unique);
kind user
  • 40,029
  • 7
  • 67
  • 77
1

You can use Array.filter.

Here in this snippet, it checks whether every element of array1 is part of array2 using filter and includes

var array1 = ["ab", "xyz", "qr", "pqrs"]
var array2 = ["ab", "def", "lmno", "def", "qr", "pqrs"]

var unique = array1.filter(cur => !array2.includes(cur))
console.log(unique)
tanmay
  • 7,761
  • 2
  • 19
  • 38