Monday, November 18, 2024
Google search engine
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

Recent Comments