Simplest code for array intersection in JavaScript?


Let’s say the following are our arrays −

var firstNamesArray=["John","David","Bob","Sam","Carol"];
var secondNamesArray=["Mike","Carol","Adam","David"];

The easiest way to perform array intersection is by using filter() along with includes(). Following is the code −

Example

var firstNamesArray=["John","David","Bob","Sam","Carol"];
var secondNamesArray=["Mike","Carol","Adam","David"];
var intersectionOfArray=[];
intersectionOfArray=firstNamesArray.filter(v =>
secondNamesArray.includes(v));
console.log("Intersection of two array=");
console.log(intersectionOfArray);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo141.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo141.js
Intersection of two array=
[ 'David', 'Carol' ]

Updated on: 11-Sep-2020

91 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements