
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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' ]
- Related Articles
- What is the easiest code for array intersection in JavaScript?
- Finding array intersection and including repeating elements in JavaScript
- How to do multidimensional array intersection using JavaScript?
- How to Create an Array using Intersection of two Arrays in JavaScript?
- JavaScript code for recursive Fibonacci series
- Check for Valid hex code - JavaScript
- Sum array of rational numbers and returning the result in simplest form in JavaScript
- Unique intersection of arrays in JavaScript
- Intersection of two arrays JavaScript
- Simplest way to detect keypresses in JavaScript?
- Get intersection between two ranges in JavaScript
- Intersection of three sorted arrays in JavaScript
- JavaScript code to print last element of an array
- Finding intersection of multiple arrays - JavaScript
- Finding intersection of arrays of intervals in JavaScript

Advertisements