Skip to content
Related Articles

Related Articles

Lodash _.unionWith() Method

Improve Article
Save Article
Like Article
  • Last Updated : 01 Sep, 2020

The _.unionWith() method accepts 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: This method accepts two parameters as mentioned above and described below:

  • 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: Here, const _ = require(‘lodash’) is used to import the lodash library into the file.

Javascript




// Requiring the lodash library  
const _ = require("lodash");  
  
// Original array
var objects = [{ 'a': 1, 'b': 2 }];
var 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:  

Javascript




// Requiring the lodash library  
const _ = require("lodash");  
  
// Original array
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
var 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 }]
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!