當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Lodash _.uniqBy()用法及代碼示例

_.uniqBy方法類似於_.uniq,不同之處在於它接受為數組中的每個元素調用的iteratee,以生成用於計算唯一性的標準。結果值的順序由它們在數組中出現的順序決定。

用法:

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

參數:該方法接受上述和以下所述的兩個參數:

  • [數組]:此參數保存要檢查的陣列。
  • [iteratee = _。identity](函數):此參數保存每個元素調用的iteratee。

返回值:此方法用於返回新的重複自由數組。

範例1:在這裏,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);

輸出:

[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。




相關用法


注:本文由純淨天空篩選整理自shivanisinghss2110大神的英文原創作品 Lodash _.uniqBy() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。