DEV Community

gangls
gangls

Posted on

Answer: How to get the difference between two arrays in JavaScript?

Array.prototype.includes() (ES2016/ ES7) comes in handy here.


Intersection

let intersection = arr1.filter(x => arr2.includes(x))

Intersection Venn Diagram

Yields values which are present in both arr1 and arr2.

  • [1,2,3] and [2,3] will yield [2,3]
  • [1,2,3] and [2,3,5] will also yield [2,3]

Difference

(Values in just A.)

let difference = arr1.filter(x => !arr2.includes(x));

Right difference Venn Diagram

Yields…

Top comments (0)