Friday, May 8, 2026
HomeLanguagesJavascriptLodash _.unionWith() Method

Lodash _.unionWith() Method

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 }]
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32514 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6892 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12107 POSTS0 COMMENTS
Shaida Kate Naidoo
7016 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6975 POSTS0 COMMENTS
Umr Jansen
6962 POSTS0 COMMENTS