Open In App

Lodash _.unionWith() Method

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:

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.




// Requiring the lodash library 
const _ = require("lodash");
 
// Original array
let objects = [{ 'a': 1, 'b': 2 }];
let others = [{ 'b': 2 }];
 
// Use of _.unionWith() method
let gfg = _.unionWith(objects, others, _.isMatch);
 
// Printing the output 
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.




// Requiring the lodash library 
const _ = require("lodash");
 
// Original array
let objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
let others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
 
// Use of _.unionWith() method
let gfg = _.unionWith(objects, others, _.isEqual);
 
// Printing the output 
console.log(gfg)

Output:

[{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
Article Tags :