by Sai gowtham

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.

Top Udemy Courses

JavaScript - The Complete Guide 2021 (Beginner + Advanced)
JavaScript - The Complete Guide 2021 (Beginner + Advanced)
64,026 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
152,857 students enrolled
48.5 hours of video content
View Course