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 varobjects = [{ 'a': 1, 'b': 2 }]; varothers = [{ '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 varobjects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; varothers = [{ '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, zambiatek 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!
 
				 
					


