Lodash _.uniqBy() Method

Last Updated : 2 Sep, 2024

Lodash _.uniqBy method is similar to _.uniq except that it accepts iteratee which is invoked for each element in an array to generate the criterion by which uniqueness is computed. The order of result values is determined by the order they occur in the array.

Syntax:

_.uniqBy([array], [iteratee = _.identity]) 

Parameters:

  • [arrays]: This parameter holds the arrays to inspect.
  • [iteratee=_.identity]: This parameter holds the iteratee invoked per element.

Return Value:

  • This method is used to return the new duplicate free array.

Example 1: In this example, we use Lodash _.uniqBy() method to remove the duplicate values from the array ensuring only unique values are left in the array.

javascript
// Requiring the lodash library 
const _ = require("lodash");

// Original array 
let y = ([2.4, 1.6, 2.2, 1.3]);

// Use of _.uniqBy() 
// method

let gfg = _.uniqBy(y, Math.floor);

// Printing the output 
console.log(gfg);

Output: 

[2.4, 1.6 ]

Example 2: In this example, we use Lodash _.uniqBy() method to remove the duplicate values of x based on properties.

javascript
// Requiring the lodash library 
const _ = require("lodash");

// Original array 
let y = ([{ 'x': 2 }, { 'x': 2 }, { 'x': 1 }]);

// Use of _.uniqBy() 
// method
// The `_.property` iteratee shorthand.
let gfg = _.uniqBy(y, 'x');

// Printing the output 
console.log(gfg);

Output: 

[ { 'x': 2 }, { 'x': 1 } ] 

Example 3: In this example, we remove duplicate strings from an array using Lodash’s _.uniqBy() method.

javascript
// Requiring the lodash library 
const _ = require("lodash");

// Original array 
let y = (['aee', 'bee', 'bee', 'cee', 'eee',

    'dee', 'gee', 'dee']);

// Use of _.uniqBy() 
// method
// The `_.property` iteratee shorthand.
let gfg = _.uniqBy(y);

// Printing the output 
console.log(gfg);

Output: 

[ 'aee', 'bee', 'cee', 'eee', 'dee', 'gee' ] 
Comment