Simplest code for array intersection in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

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' ]
raja
Published on 11-Sep-2020 07:03:46
Advertisements