Lodash _.unionWith() Method
Last Updated :
30 Oct, 2023
Lodash _.unionWith() method accepts a comparator which is invoked to compare elements of arrays. The order of result values is determined from the first array in which the value occurs. The comparator is invoked with two arguments: (arrVal, othVal).
Syntax:
_.unionWith(array, [comparator]);
Parameters:
- array: This parameter holds the array to inspect.
- [comparator]: This parameter holds the comparator invoked per element.
Return Value:
This method is used to return the new array of combined values.
Example 1: In this example, we are getting the union of the given two arrays by the use of the lodash _.unionWith() method.
Javascript
const _ = require( "lodash" );
let objects = [{ 'a' : 1, 'b' : 2 }];
let others = [{ 'b' : 2 }];
let gfg = _.unionWith(objects, others, _.isMatch);
console.log(gfg)
|
Output:
[{'a': 1, 'b': 2 }, { 'b': 2}]
Example 2: In this example, we are getting the union of the given two arrays by the use of the lodash _.unionWith() method.
Javascript
const _ = require( "lodash" );
let objects = [{ 'x' : 1, 'y' : 2 }, { 'x' : 2, 'y' : 1 }];
let others = [{ 'x' : 1, 'y' : 1 }, { 'x' : 1, 'y' : 2 }];
let gfg = _.unionWith(objects, others, _.isEqual);
console.log(gfg)
|
Output:
[{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
Share your thoughts in the comments
Please Login to comment...