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

To use the intersectionWith function from the lodash library in TypeScript, you can follow these steps:

  1. Install the @types/lodash package to get type annotations for lodash:
npm install --save-dev @types/lodash
37 chars
2 lines
  1. Import the intersectionWith function from lodash:
index.ts
import { intersectionWith } from 'lodash';
43 chars
2 lines
  1. Create a typed callback function to compare the intersecting values:
index.ts
interface MyType {
  id: number;
  name: string;
}

const compareFn = (arrVal: MyType, othVal: MyType) => {
  return arrVal.id === othVal.id;
};
145 chars
9 lines
  1. Call the intersectionWith function with the arrays to find the intersection:
index.ts
const array1: MyType[] = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' },
];

const array2: MyType[] = [
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' },
  { id: 4, name: 'Dave' },
];

const result = intersectionWith(array1, array2, compareFn);
console.log(result); // [{ id:2, name:'Bob' }, { id:3, name:'Charlie' }]
362 chars
15 lines

In this example, the intersectionWith function returns an array of the intersecting objects from array1 and array2, using the compareFn function to compare the id property of each object.

gistlibby LogSnag