Lodash _.sumBy() Method
Last Updated :
25 Oct, 2023
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:
- 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: In this example, we are returning the sum of an array having objects as values by the use of the _.sumBy() method.
Javascript
const _ = require( "lodash" );
let arr = [{ 'n' : 4 }, { 'n' : 2 }, { 'n' : 6 }];
let gfg = _.sumBy(arr, function (o) { return o.n; });
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.
Javascript
const _ = require( "lodash" );
let arr = [{ 'n' : 10 }, { 'n' : 5 }, { 'n' : 3 }, { 'n' : 12 }];
let gfg = _.sumBy(arr, 'n' );
console.log(gfg);
|
Output:
30
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...