how to use the unionwith function from lodash in javascript

The unionWith function from lodash allows you to find the union of two arrays (i.e. the elements that are present in both arrays) using a comparator function that you specify.

The syntax for using unionWith is as follows:

index.tsx
_.unionWith(array, [values], [comparator])
43 chars
2 lines

where:

  • array (Array): The array to inspect.
  • [values] (Array): The values to exclude.
  • [comparator] (Function): The comparator function invoked per element.

Here's an example of how to use unionWith:

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

const array1 = [{ x: 1, y: 1 }, { x: 2, y: 2 }];
const array2 = [{ x: 1, y: 2 }, { x: 3, y: 4 }];

const result = _.unionWith(array1, array2, _.isEqual);

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

In this example, we are finding the union of array1 and array2 using the isEqual function as the comparator. This function is used to compare each element of the arrays to determine if they are equal.

The result variable will contain an array with the elements that are present in both array1 and array2, using the isEqual comparator function to determine equality.

gistlibby LogSnag