How to use Lodash Library In Javascript
Using the Lodash library, the xor function computes the symmetric difference between two arrays, returning an array of elements that are unique to each input array. This approach simplifies the process by leveraging Lodash’s built-in utility functions.
Example: In this example we are using lodash library’s xor function to compute the symmetric difference between array1 and array2, returning elements present in one array but not both. The result is logged to the console.
const _ = require('lodash');
const array1 = [1, 2, 3];
const array2 = [3, 4, 5];
const symmetricDifference = _.xor(array1, array2);
console.log(symmetricDifference);
Output:
[1, 2, 4, 5]
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: