Friday, November 21, 2025
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

Most Popular

Dominic
32405 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6781 POSTS0 COMMENTS
Nicole Veronica
11928 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11997 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7166 POSTS0 COMMENTS
Thapelo Manthata
6862 POSTS0 COMMENTS
Umr Jansen
6847 POSTS0 COMMENTS