This post will discuss how to find the intersection of two arrays in JavaScript. In order words, list out the common values present in each of the arrays.

For example, the intersection of arrays [1,2,3,4] and [3,4,5] is [3,4].

1. Using Array.prototype.filter() function

The idea is to check the presence of each element of the first array in the second array. This can be easily done using the indexOf() method with the filter() method in the following manner:

Download  Run Code

 
To check for the presence of a certain element in an array, you can also use the latest includes() method, which returns a boolean value. This is demonstrated below:

Download  Run Code

 
Note this solution doesn’t result in unique values in the output.

2. Using Set

Another solution is to convert the array into an ES6 Set and call its has() method to check for the other array elements.

Download  Run Code

 
To avoid printing duplicates in the output, you can remove duplicate items from the first array, as shown below:

Download  Run Code

3. Using Lodash/Underscore Library

In case you don’t want to use Set as an intermediate data structure for finding common values, the code can be simplified using underscore or lodash library. The following code example prints the unique values present in given arrays using the intersection() method.

Download Code

4. Using jQuery

With jQuery, you can use the following code:

Download Code

 
The code can be simplified using jQuery filter() method:

Download Code

That’s all about finding the intersection of two arrays in JavaScript.