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
Finding deviations in two Number arrays in JavaScript
We are required to write a JavaScript function that takes in two number arrays and returns the elements that are not common to both arrays (symmetric difference).
For example, if the two arrays are:
const arr1 = [2, 4, 2, 4, 6, 4, 3]; const arr2 = [4, 2, 5, 12, 4, 1, 3, 34];
Then the output should be:
[6, 5, 12, 1, 34]
Method 1: Using indexOf() Method
This approach uses nested loops to check if elements exist in the other array:
const arr1 = [2, 4, 2, 4, 6, 4, 3];
const arr2 = [4, 2, 5, 12, 4, 1, 3, 34];
const deviations = (first, second) => {
const res = [];
// Check elements in first array that don't exist in second
for(let i = 0; i < first.length; i++){
if(second.indexOf(first[i]) === -1){
res.push(first[i]);
}
}
// Check elements in second array that don't exist in first
for(let j = 0; j < second.length; j++){
if(first.indexOf(second[j]) === -1){
res.push(second[j]);
}
}
return res;
};
console.log(deviations(arr1, arr2));
[6, 5, 12, 1, 34]
Method 2: Using Set for Better Performance
Using Set provides O(1) lookup time instead of O(n) with indexOf:
const arr1 = [2, 4, 2, 4, 6, 4, 3];
const arr2 = [4, 2, 5, 12, 4, 1, 3, 34];
const findDeviations = (first, second) => {
const set1 = new Set(first);
const set2 = new Set(second);
const result = [];
// Add elements from first array not in second
for(let item of set1) {
if(!set2.has(item)) {
result.push(item);
}
}
// Add elements from second array not in first
for(let item of set2) {
if(!set1.has(item)) {
result.push(item);
}
}
return result;
};
console.log(findDeviations(arr1, arr2));
[6, 5, 12, 1, 34]
Method 3: Using filter() Method
A more functional approach using array methods:
const arr1 = [2, 4, 2, 4, 6, 4, 3];
const arr2 = [4, 2, 5, 12, 4, 1, 3, 34];
const getDeviations = (first, second) => {
const unique1 = [...new Set(first)];
const unique2 = [...new Set(second)];
const diff1 = unique1.filter(x => !unique2.includes(x));
const diff2 = unique2.filter(x => !unique1.includes(x));
return [...diff1, ...diff2];
};
console.log(getDeviations(arr1, arr2));
[6, 5, 12, 1, 34]
Performance Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| indexOf() | O(n²) | O(1) | Small arrays |
| Set | O(n) | O(n) | Large arrays |
| filter() | O(n²) | O(n) | Functional style |
Conclusion
The Set-based approach offers the best performance for large arrays, while indexOf() is simpler for smaller datasets. Choose the method based on your data size and performance requirements.
Advertisements
