Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Taking common elements from many arrays in 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.
This problem requires finding the intersection of multiple arrays, which means identifying elements that exist in every provided array.
Understanding the Problem
The intersection of arrays means finding elements that appear in all arrays. For example, if we have arrays [1, 2, 3], [2, 3, 4], and [3, 4, 5], the common element is 3.
Example Implementation
Here's a solution that uses a helper function to find intersection between two arrays, then applies it to all 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];
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));
[2, 1, 3]
How It Works
The solution uses two functions:
- intersection(): Finds common elements between two arrays by checking if each element in the first array exists in the second array
- intersectMany(): Takes multiple arrays using rest parameters (...arrs) and progressively finds intersection with each subsequent array
Alternative Approach Using Set
Here's a more efficient approach using Set for better performance:
const findCommonElements = (...arrays) => {
if (arrays.length === 0) return [];
// Start with first array as base
let result = [...new Set(arrays[0])];
// Filter elements that exist in all subsequent arrays
for (let i = 1; i < arrays.length; i++) {
const currentSet = new Set(arrays[i]);
result = result.filter(element => currentSet.has(element));
}
return result;
};
const testArr1 = [1, 2, 3, 4, 5];
const testArr2 = [3, 4, 5, 6, 7];
const testArr3 = [4, 5, 7, 8, 9];
console.log(findCommonElements(testArr1, testArr2, testArr3));
[4, 5]
Edge Cases
The function handles common edge cases:
// No common elements console.log(findCommonElements([1, 2], [3, 4], [5, 6])); // Single array console.log(findCommonElements([1, 2, 3])); // Empty arrays console.log(findCommonElements([], [1, 2], [3, 4]));
[] [1, 2, 3] []
Conclusion
Finding common elements from multiple arrays can be achieved by progressively filtering elements that exist in all arrays. The Set-based approach offers better performance for larger datasets by providing O(1) lookup time.
