Lodash _.uniqWith() Method
Last Updated :
27 Oct, 2023
Lodash _.uniqWith() method is similar to the _.uniq() method ( i.e. it creates a duplicate-free version of an array, in which only the first occurrence of each element is kept.) except that it accepts comparator which is invoked to compare elements of an array. The order of result values is determined by the order they occur in the array.
Syntax:
_.uniqWith(array, [comparator]);
Parameters:
- array: This parameter holds the array to inspect.
- [comparator] (Function): This parameter holds the comparator invoked per element and is invoked with two arguments (arrVal, othVal).
Return Value:
This method returns the new duplicate free array.
Example 1: In this example, we are using the lodash _.uniqWith() method in which we are passing a function and an array that the function is invoking at each iteration of the array and printing the unique elements of the array in the console.
javascript
const _ = require( "lodash" );
let objects = [{ 'x' : 5, 'y' : 2 }, {
'x' : 3, 'y' :
4
}, { 'x' : 5, 'y' : 2 }];
let gfg = _.uniqWith(objects, _.isEqual);
console.log(gfg);
|
Output:
[ { x: 5, y: 2 }, { x: 3, y: 4 } ]
Example 2: In this example, we are using the lodash _.uniqWith() method in which we are passing a function and an array that function is invoking at each iteration of the array and printing the unique elements of the array in the console.
javascript
const _ = require( "lodash" );
let objects = [2.2, 3.2, 4.2, 3.2, 5.2, 4.2];
let gfg = _.uniqWith(objects, _.isEqual);
console.log(gfg);
|
Output:
[ 2.2, 3.2, 4.2, 5.2]
Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...