HomeLanguagesJavascriptLodash _.sumBy() Method

Lodash _.sumBy() Method

Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.

The _.sumBy() method is used to compute the sum from the original array by iterating over each element in the array by using the Iteratee function. It is almost the same as _.sum() method.

Syntax:

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

Parameters: This method accepts two parameters as mentioned above and described below:

  • array: This parameter holds the array to iterate over.
  • [iteratee = _.identity]:  This parameter holds the iteratee invoked per element.

Return Value: This method returns the sum.

Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library into the file.

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


Output:

12

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


Output:

30
RELATED ARTICLES

6 COMMENTS

Most Popular

Dominic
32688 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7057 POSTS0 COMMENTS
Nicole Veronica
12198 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12293 POSTS0 COMMENTS
Shaida Kate Naidoo
7182 POSTS0 COMMENTS
Ted Musemwa
7447 POSTS0 COMMENTS
Thapelo Manthata
7160 POSTS0 COMMENTS
Umr Jansen
7150 POSTS0 COMMENTS