Lodash _.uniqWith() Method

The _.uniqWith() method is similar to _.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. Order of result values is determined by the order they occur in the array.

Syntax:

_.uniqWith(array, [comparator])

Parameters: This method accepts two parameters as mentioned above and described below:

  • 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: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.



javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Requiring the lodash library 
const _ = require("lodash"); 
      
// Original array 
var 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);

chevron_right


Output:

[ { x: 5, y: 2 }, { x: 3, y: 4 } ]

Example 2:

javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Requiring the lodash library 
const _ = require("lodash"); 
      
// Original array 
var 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);

chevron_right


Output:

[ 2.2, 3.2, 4.2, 5.2]

Example 3:

javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Requiring the lodash library 
const _ = require("lodash"); 
      
// Original array 
var objects = ['p', 'q', 'r'
      'u', 's', 't', 'r', 'u'];    
  
// Use of _.uniqWith() method
let gfg = _.uniqWith(objects, _.isEqual);
      
// Printing the output 
console.log(gfg);

chevron_right


Output:

['p', 'q', 'r', 'u', 's', 't']

Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.

full-stack-img




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.