Approach 4:Using reduce() and includes() Methods
This method iterates over the first array and checks if each element is present in the second array using the includes() method. It accumulates the elements that are not found in the second array, resulting in the difference between the two arrays.
Syntax:
const difference = array1.reduce((result, element) => {
if (array2.indexOf(element) === -1) {
result.push(element);
}
return result;
}, []);
Example: In this example, we will get the differences of arrays using reduce() and includes() methods and show the combined result as output:
// Defining two arrays
const array1 = [1, 2, 3, 4, 5, 7, 9];
const array2 = [5, 6, 7, 8, 9];
// Getting elemment in array1 but not in array2
const difference1 = array1.reduce((result, element) => {
if (array2.indexOf(element) === -1) {
result.push(element);
}
return result;
}, []);
// Getting elemements in array2 but not in array1
const difference2 = array2.reduce((result, element) => {
if (array1.indexOf(element) === -1) {
result.push(element);
}
return result;
}, []);
// Combining the diffeerence using spread operator
const result = [...difference1, ...difference2];
// Show the result as output
console.log(result);
Output
[ 1, 2, 3, 4, 6, 8 ]
How to get symmetric difference between two arrays in JavaScript ?
In this article, we will see how to get the symmetric difference between two arrays using JavaScript.
In Mathematics the symmetric difference between two sets A and B is represented as A Δ B = (A – B) ∪ (B – A)
- It is defined as a set of all elements that are present in either set A or set B but not in both.
- In simple words, common elements are discarded from both sets.
For example:
A = { 1, 2, 3, 4, 5, 6}
B = { 4, 5, 6, 7 }
A - B = { 1, 2, 3, 4, 5, 6} - { 4, 5, 6, 7 }
= { 1, 2, 3 }
B - A = { 4, 5, 6, 7 } - { 1, 2, 3, 4, 5, 6}
= { 7, 1, 2, 3 }
A Δ B = ( A - B ) ∪ ( B - A )
= { 1, 2, 3 } ∪ { 7, 1, 2, 3 }
A Δ B = { 1, 2, 3, 7 }
We can achieve this with the following approaches: