by Sai gowtham

How to find the intersection of arrays in JavaScript

Home » javascript » How to find the intersection of arrays in JavaScript

In this tutorial, we are going to learn about the intersection of two arrays in JavaScript with the help of examples.

Consider we have two arrays like this.

const arr1 = [1,2,3,4];
const arr2 = [1,2,5,6];

The intersection of the above two arrays is [1,2].

Let’s solve this problem by using JavaScript filter() and includes() methods.

Example:

const arr1 = [1,2,3,4];
const arr2 = [1,2,5,6];

const intersection = arr1.filter(value=>arr2.includes(value));
console.log(intersection); // [1,2]

In the above code, on each iteration, the filter method only kept the values that returns true.

The includes() method takes the value as an argument and returns true if a value is found in the array else it returns false.