how to use the xorwith function from lodash in javascript

The xorWith() function from Lodash library is used to create an array of unique values that is symmetric difference of two arrays that are compared by using a comparator function. Here's an example of how to use xorWith() function:

index.tsx
const _ = require('lodash');

const arr1 = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
const arr2 = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];

const result = _.xorWith(arr1, arr2, _.isEqual);

console.log(result); // [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
256 chars
9 lines

In this example, we first require the Lodash library using const _ = require('lodash'). Then we define two arrays, arr1 and arr2 that we want to compare.

The xorWith() function takes three parameters: the first two parameters are the arrays to be compared and the third parameter is the comparator function used to compare values in the arrays.

In this example, we use _.isEqual function as the comparator function to compare the values in arr1 and arr2. _.isEqual is a method that checks if two given values are equal, returning true if they are, false otherwise.

Finally, the result array contains the symmetric difference of arr1 and arr2, which are the unique values in each array that are not contained in the other. In this case, the result contains the elements { 'x': 2, 'y': 1 } and { 'x': 1, 'y': 1 }.

gistlibby LogSnag