- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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' ]
Advertisements