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
Unique intersection of arrays in JavaScript
We are required to write a JavaScript function that takes in two arrays of numbers, let's say arr1 and arr2. The function should find the intersection between the elements of the array. i.e., the elements that appear in both the arrays.
The only condition is that if we encountered one element before as intersected, we should not consider it again even if appears again in both the arrays.
For example ?
If the input arrays are ?
const arr1 = [1, 5, 7, 3, 1]; const arr2 = [1, 7, 3, 1, 6];
Then the output array should be ?
const output = [1, 3, 7];
However, the order is not that important, what's more important is not to consider repetitive intersection.
Using Set-Based Approach
The most efficient approach uses a Set to track elements from the first array, then iterates through the second array to find matches:
const arr1 = [1, 5, 7, 3, 1];
const arr2 = [1, 7, 3, 1, 6];
const uniqueIntersection = (arr1, arr2) => {
const map = new Set();
const res = [];
arr1.forEach(el => map.add(el));
arr2.forEach(el => {
if (map.has(el)) {
res.push(el);
map.delete(el);
}
});
return res;
};
console.log(uniqueIntersection(arr1, arr2));
[1, 7, 3]
How It Works
The algorithm works in three steps:
- Create a Set: Add all elements from the first array to a Set for O(1) lookup
- Find Intersections: Iterate through the second array, checking if each element exists in the Set
- Ensure Uniqueness: Delete matched elements from the Set to prevent duplicates in results
Alternative Using Array Methods
You can also use array methods with a Set for a more functional approach:
const arr1 = [1, 5, 7, 3, 1];
const arr2 = [1, 7, 3, 1, 6];
const uniqueIntersection2 = (arr1, arr2) => {
const set1 = new Set(arr1);
const set2 = new Set(arr2);
return [...set1].filter(x => set2.has(x));
};
console.log(uniqueIntersection2(arr1, arr2));
[1, 5, 7, 3]
Performance Comparison
| Method | Time Complexity | Space Complexity | Order Preserved |
|---|---|---|---|
| Set with deletion | O(n + m) | O(n) | Second array order |
| Set filtering | O(n + m) | O(n + m) | First array order |
Conclusion
The Set-based approach efficiently finds unique intersections by leveraging O(1) lookup time. The deletion method preserves the second array's order while ensuring no duplicate intersections.
