Friday, October 24, 2025
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

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS