Open In App

Lodash _.unionWith() Method

Improve
Improve
Like Article
Like
Save
Share
Report

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




// 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.

Javascript




// 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 }]

Last Updated : 30 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads