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
Selected Reading
Compare two arrays and get those values that did not match JavaScript
We have two arrays of literals that contain some common values, our job is to write a function that returns an array with all those elements from both arrays that are not common.
For example ?
// if the two arrays are: const first = ['cat', 'dog', 'mouse']; const second = ['zebra', 'tiger', 'dog', 'mouse']; // then the output should be: const output = ['cat', 'zebra', 'tiger'] // because these three are the only elements that are not common to both arrays
Let's write the code for this ?
We will spread the two arrays and filter the resulting array to obtain an array that contains no common elements like this ?
Using Spread and Filter
const first = ['cat', 'dog', 'mouse'];
const second = ['zebra', 'tiger', 'dog', 'mouse'];
const removeCommon = (first, second) => {
const spreaded = [...first, ...second];
return spreaded.filter(el => {
return !(first.includes(el) && second.includes(el));
})
};
console.log(removeCommon(first, second));
[ 'cat', 'zebra', 'tiger' ]
Using Sets for Better Performance
For larger arrays, using Sets provides better performance due to O(1) lookup time:
const first = ['cat', 'dog', 'mouse', 'elephant'];
const second = ['zebra', 'tiger', 'dog', 'mouse', 'lion'];
const removeCommonWithSets = (arr1, arr2) => {
const set1 = new Set(arr1);
const set2 = new Set(arr2);
const unique1 = arr1.filter(item => !set2.has(item));
const unique2 = arr2.filter(item => !set1.has(item));
return [...unique1, ...unique2];
};
console.log(removeCommonWithSets(first, second));
[ 'cat', 'elephant', 'zebra', 'tiger', 'lion' ]
Handling Duplicates
If you want to remove duplicates from the result:
const first = ['cat', 'dog', 'mouse', 'cat'];
const second = ['zebra', 'tiger', 'dog', 'zebra'];
const removeCommonUnique = (arr1, arr2) => {
const set1 = new Set(arr1);
const set2 = new Set(arr2);
const unique1 = [...set1].filter(item => !set2.has(item));
const unique2 = [...set2].filter(item => !set1.has(item));
return [...unique1, ...unique2];
};
console.log(removeCommonUnique(first, second));
[ 'cat', 'mouse', 'zebra', 'tiger' ]
Comparison
| Method | Time Complexity | Handles Duplicates |
|---|---|---|
| Spread + Filter | O(n²) | Preserves duplicates |
| Sets | O(n) | Can remove or preserve |
Conclusion
Use the spread and filter approach for simple cases. For larger arrays or when performance matters, the Sets method is more efficient with O(n) time complexity.
Advertisements
