how to use the differencewith function from lodash in javascript

The differenceWith() function from lodash library in JavaScript is used to compare two arrays and return a new array with values from the first array that do not exist in the second array, based on a given comparator function.

Here is an example of how to use the differenceWith() function:

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

const arr1 = [{id: 1, name: 'John'}, {id: 2, name: 'Mary'}, {id: 3, name: 'Jane'}, {id: 4, name: 'Bob'}];
const arr2 = [{id: 1, name: 'John'}, {id: 2, name: 'Mary'}];

const comparator = (arrVal, othVal) => {
  return arrVal.id === othVal.id;
};

const result = _.differenceWith(arr1, arr2, comparator);

console.log(result); // Output: [{id: 3, name: 'Jane'}, {id: 4, name: 'Bob'}]
413 chars
13 lines

In the above example, arr1 and arr2 are two arrays that we want to compare. We have defined a comparator function that compares values based on the id property of each object. The differenceWith() function is then called on arr1 and arr2 with the comparator function as an argument, which returns a new array containing values from arr1 that do not exist in arr2. The resulting array is stored in the result variable and then logged to the console.

gistlibby LogSnag