📜  Lodash _.uniqBy() 方法

📅  最后修改于: 2022-05-13 01:56:23.389000             🧑  作者: Mango

Lodash _.uniqBy() 方法

_.uniqBy 方法与 _.uniq 类似,只是它接受 iteratee,它为数组中的每个元素调用以生成计算唯一性的标准。结果值的顺序由它们在数组中出现的顺序决定。
句法:

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

参数:此方法接受上面提到的两个参数,如下所述:

  • [arrays]:此参数保存要检查的数组。
  • [iteratee=_.identity](函数):此参数保存每个元素调用的 iteratee。

返回值:该方法用于返回新的重复空闲数组。
示例一:这里使用 const _ = require('lodash') 来导入文件中的 lodash 库。

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


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


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


输出:

[2.4, 1.6 ]

示例 2:

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

输出:

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

示例 3:

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

输出:

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

注意:此代码在普通 JavaScript 中不起作用,因为它需要安装库 lodash。