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 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 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 JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course