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


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

Lodash是一個JavaScript庫,可在underscore.js之上運行。 Lodash幫助處理數組,字符串,對象,數字等。

_.sumBy()方法用於通過使用Iteratee函數遍曆數組中的每個元素來從原始數組計算總和。它與_.sum()方法幾乎相同。

用法:

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

參數:此方法接受上麵提到和下麵描述的兩個參數:

  • array:此參數保存要迭代的數組。
  • [iteratee = _.identity]:此參數保存每個元素調用的iteratee。

返回值:此方法返回總和。



範例1:在這裏,const _ = require(‘lodash’)用於將lodash庫導入文件中。

Javascript

// Requiring the lodash library   
const _ = require("lodash");   
   
// Original array  
var arr = [{ 'n':4 }, { 'n':2 }, { 'n':6 }]; 
     
// Use of _.sumBy()   
// method  
let gfg = _.sumBy(arr, function(o) { return o.n; });  
         
// Printing the output   
console.log(gfg);

輸出:

12

範例2:

Javascript

// Requiring the lodash library   
const _ = require("lodash");   
   
// Original array  
var arr = [{ 'n':10 }, { 'n':5 }, { 'n':3 }, { 'n':12 }]; 
     
// Use of _.sumBy()   
// method  
let gfg = _.sumBy(arr, 'n');  
         
// Printing the output   
console.log(gfg);

輸出:

30

相關用法


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