-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

2
  • 1
    @str the question u posted is using jquery and i needed a solution with javascript. Commented Apr 25, 2017 at 10:55
  • But the answers do not (at least not all of them). Commented Apr 25, 2017 at 10:56

2 Answers 2

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);

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

Comments

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)

1 Comment

@downvoter, what's wrong with this answer?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.