Friday, November 14, 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
32399 POSTS0 COMMENTS
Milvus
95 POSTS0 COMMENTS
Nango Kala
6765 POSTS0 COMMENTS
Nicole Veronica
11917 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11984 POSTS0 COMMENTS
Shaida Kate Naidoo
6889 POSTS0 COMMENTS
Ted Musemwa
7142 POSTS0 COMMENTS
Thapelo Manthata
6837 POSTS0 COMMENTS
Umr Jansen
6840 POSTS0 COMMENTS