- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Finding intersection of multiple arrays - JavaScript
We are required to write a JavaScript function that takes in any arbitrary number of arrays and returns an array of elements that are common to all arrays. If there are no common elements, then we should return an empty array.
Let’s say the following are our arrays −
const arr1 = [2, 6, 7, 1, 7, 8, 4, 3]; const arr2 = [5, ,7, 2, 2, 1, 3]; const arr3 = [1, 56, 345, 6, 54, 2, 68, 85, 3];
Example
Following is the code −
const arr1 = [2, 6, 7, 1, 7, 8, 4, 3]; const arr2 = [5, ,7, 2, 2, 1, 3]; const arr3 = [1, 56, 345, 6, 54, 2, 68, 85, 3]; const intersection = (arr1, arr2) => { const res = []; for(let i = 0; i < arr1.length; i++){ if(!arr2.includes(arr1[i])){ continue; }; res.push(arr1[i]); }; return res; }; const intersectMany = (...arrs) => { let res = arrs[0].slice(); for(let i = 1; i < arrs.length; i++){ res = intersection(res, arrs[i]); }; return res; }; console.log(intersectMany(arr1, arr2, arr3));
Output
This will produce the following output in console −
[2, 1, 3]
- Related Articles
- Finding the intersection of arrays of strings - JavaScript
- Finding intersection of arrays of intervals in JavaScript
- Finding intersection of arrays that contain repetitive entries in JavaScript
- Intersection of two arrays JavaScript
- Unique intersection of arrays in JavaScript
- Intersection of three sorted arrays in JavaScript
- Finding the inclination of arrays in JavaScript
- Finding array intersection and including repeating elements in JavaScript
- Finding reversed index of elements in arrays - JavaScript
- Finding the continuity of two arrays in JavaScript
- Python - Intersection of multiple lists
- Cartesian product of multiple arrays in JavaScript
- Intersection of two arrays in Java
- Intersection of two arrays in C#
- Intersection of Two Arrays in C++

Advertisements