Open In App

Lodash _.sumBy() Method

Lodash _.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 the _.sum() method.

Syntax:

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

Parameters:

Return Value:

This method returns the sum.



Example 1: In this example, we are returning the sum of an array having objects as values by the use of the _.sumBy() method.




// Requiring the lodash library 
const _ = require("lodash");
 
// Original array
let 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: In this example, we are returning the sum of an array having objects as values by the use of the _.sumBy() method.




// Requiring the lodash library 
const _ = require("lodash");
 
// Original array
let 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
Article Tags :