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
Deviations in two JavaScript arrays in JavaScript
We have two arrays of numbers and need to find elements that exist in one array but not in both. This is called finding the symmetric difference or deviation between arrays.
const arr1 = [12, 54, 2, 4, 6, 34, 3]; const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];
We need to write a JavaScript function that takes two arrays and returns elements that are not common to both arrays.
Using indexOf() Method
The basic approach uses indexOf() to check if elements exist in the other array:
const arr1 = [12, 54, 2, 4, 6, 34, 3];
const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];
const difference = (first, second) => {
const res = [];
// Find elements in first array but not in second
for(let i = 0; i
[ 6, 5, 1 ]
Using Set and filter() Method
A more modern approach using Sets for better performance:
const arr1 = [12, 54, 2, 4, 6, 34, 3];
const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];
const differenceWithSet = (first, second) => {
const set1 = new Set(first);
const set2 = new Set(second);
const diff1 = first.filter(x => !set2.has(x));
const diff2 = second.filter(x => !set1.has(x));
return [...diff1, ...diff2];
};
console.log(differenceWithSet(arr1, arr2));
[ 6, 5, 1 ]
How It Works
Both methods find elements that exist in one array but not the other:
- 6 - exists in arr1 but not in arr2
- 5 - exists in arr2 but not in arr1
- 1 - exists in arr2 but not in arr1
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| indexOf() | O(n²) | O(1) | Good |
| Set + filter() | O(n) | O(n) | Better |
Conclusion
Use the Set-based approach for better performance with large arrays. The indexOf() method works fine for smaller datasets and is easier to understand.
Advertisements
