Open In App
Related Articles

Lodash _.uniqWith() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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

// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let objects = [{ 'x': 5, 'y': 2 }, {
    'x': 3, 'y':
 
        4
}, { 'x': 5, 'y': 2 }];
 
// Use of _.uniqWith() method
let gfg = _.uniqWith(objects, _.isEqual);
 
// Printing the output
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

// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let objects = [2.2, 3.2, 4.2, 3.2, 5.2, 4.2];
 
// Use of _.uniqWith() method
let gfg = _.uniqWith(objects, _.isEqual);
 
// Printing the output
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.



Last Updated : 27 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads