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
Find the Symmetric difference between two arrays - JavaScript
In Mathematics, the symmetric difference of two sets, say A and B is represented by A ? B. It is defined as the set of all elements which belong either to A or to B but not to both.
For example:
const A = [1, 2, 3, 4, 5, 6, 7, 8]; const B = [1, 3, 5, 6, 7, 8, 9];
The symmetric difference of A and B will be:
const diff = [2, 4, 9]
Using For Loops with indexOf()
This approach iterates through both arrays and checks if each element exists in the other array:
const A = [1, 2, 3, 4, 5, 6, 7, 8];
const B = [1, 3, 5, 6, 7, 8, 9];
const symmetricDifference = (arr1, arr2) => {
const res = [];
// Add elements from arr1 not in arr2
for(let i = 0; i < arr1.length; i++){
if(arr2.indexOf(arr1[i]) === -1){
res.push(arr1[i]);
}
}
// Add elements from arr2 not in arr1
for(let i = 0; i < arr2.length; i++){
if(arr1.indexOf(arr2[i]) === -1){
res.push(arr2[i]);
}
}
return res;
};
console.log(symmetricDifference(A, B));
[2, 4, 9]
Using Set and Filter
A more modern approach using ES6 features for cleaner code:
const A = [1, 2, 3, 4, 5, 6, 7, 8];
const B = [1, 3, 5, 6, 7, 8, 9];
const symmetricDifference = (arr1, arr2) => {
const set1 = new Set(arr1);
const set2 = new Set(arr2);
const diff1 = arr1.filter(x => !set2.has(x));
const diff2 = arr2.filter(x => !set1.has(x));
return [...diff1, ...diff2];
};
console.log(symmetricDifference(A, B));
[2, 4, 9]
Using concat() and filter()
Another approach using array methods for a functional style:
const A = [1, 2, 3, 4, 5, 6, 7, 8];
const B = [1, 3, 5, 6, 7, 8, 9];
const symmetricDifference = (arr1, arr2) => {
return arr1.filter(x => !arr2.includes(x))
.concat(arr2.filter(x => !arr1.includes(x)));
};
console.log(symmetricDifference(A, B));
[2, 4, 9]
Performance Comparison
| Method | Time Complexity | Readability | Best For |
|---|---|---|---|
| For loops + indexOf() | O(n²) | Good | Small arrays |
| Set + filter() | O(n) | Excellent | Large arrays |
| concat() + filter() | O(n²) | Good | Functional style |
Conclusion
The Set-based approach offers the best performance for large arrays due to O(1) lookup time. For smaller datasets, any method works well, with the choice depending on your coding style preference.
Advertisements
