Sunday, September 22, 2024
Google search engine
HomeLanguagesJavascriptLodash _.uniqWith() Method

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




// 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);


Output:

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

Example 2:

javascript




// 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);


Output:

[ 2.2, 3.2, 4.2, 5.2]

Example 3:

javascript




// 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);


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.

RELATED ARTICLES

Most Popular

Recent Comments