how to use the differencewith function from the lodash library in typescript

To use the differenceWith function from the Lodash library in TypeScript, you must first install the library's types with the following command:

index.ts
npm install --save-dev @types/lodash
37 chars
2 lines

Once you've installed the Lodash types, you can use the differenceWith function just like you would in regular JavaScript, like so:

index.ts
import differenceWith from 'lodash/differenceWith';

interface Person {
  name: string;
  age: number;
}

const peopleA: Person[] = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 },
];

const peopleB: Person[] = [
  { name: 'Bob', age: 30 },
  { name: 'Dave', age: 40 },
];

const ageComparer = (a: Person, b: Person) => a.age === b.age;

const diff = differenceWith(peopleA, peopleB, ageComparer);

console.log(diff); // [{ name: 'Alice', age: 25 }, { name: 'Charlie', age: 35 }]
523 chars
24 lines

In this example, we have two arrays of Person objects. We want to find the difference between these arrays by comparing the age of each person. We define an ageComparer function that compares the age of two people and pass it to the differenceWith function along with the two arrays. The resulting diff array contains the people that exist in peopleA but not in peopleB.

gistlibby LogSnag