'How to find symmetrical difference using JavaScript?
I've been working on an algorithm that will find the symmetric difference of two arrays (i.e. only items that are in 1 of the 2 arrays, but not both). I've come up with the following so far:
function diffArray(arr1, arr2) {
let newArr1 = arr1.slice();
let newArr2 = arr2.slice();
if (newArr1.length > newArr2.length) {
return newArr1.filter((item) => !(item in newArr2));
} else {
return newArr2.filter((item) => !(item in newArr1));
}
};
const result = diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
console.log(result);
But when testing with diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]) the output is [4, 5] instead of just [4]. The issue seems to happen with whatever the last value of either array is, but I can't seem to figure out what about my code is causing the issue. Thanks in advance for any help.
Solution 1:[1]
The in operator checks if the value on the left matches a property name on the right.
In you want to check if one of the property values is in an array, use the includes method.
function diffArray(arr1, arr2) {
let newArr1 = arr1.slice();
let newArr2 = arr2.slice();
if (newArr1.length > newArr2.length) {
return newArr1.filter((item) => !newArr2.includes(item));
} else {
return newArr2.filter((item) => !newArr1.includes(item));
}
};
const result = diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
console.log(result);
Solution 2:[2]
Updating the answer for another condition
const result = diffArray([1, 2, 3, 4], [1, 2, 3, 5]);
function diffArray(arr1, arr2){
const diff1 = arr1.filter(item => !arr2.includes(item)); // if item not available, the value will be filtered
const diff2 = arr2.filter(item => !arr1.includes(item));// if item not available, the value will be filtered
return diff1.concat(diff2);
}
// const result = diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
const result = diffArray([1, 2, 3, 4], [1, 2, 3, 5]); // This condition will fail on the above code
console.log(result);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Quentin |
| Solution 2 | Alaksandar Jesus Gene |
