Syntax, Parameter and Return Value
Syntax:
_.sumBy(array, [iteratee=_.identity])
Parameters:
-
array (Array): The array to iterate over.
- [iteratee=_.identity] (Function|Object|String): The iteratee invoked per element to generate the criterion by which the sum is calculated.
Return Value:
(Number) - Returns the sum of the array values based on the iteratee.
Examples
Summing a Specific Property:
JavaScript
var _ = require('lodash');
var products = [
{ name: 'Product 1', quantity: 4 },
{ name: 'Product 2', quantity: 2 },
{ name: 'Product 3', quantity: 3 }
];
var totalQuantity = _.sumBy(products, (p) => p.quantity);
console.log(totalQuantity);

You can also try this code with Online Javascript Compiler
Run Code
Output:
9
Demonstrates calculating the total quantity of products.
Using Property Name Shorthand:
JavaScript
var orders = [
{ id: 1, amount: 100 },
{ id: 2, amount: 200 },
{ id: 3, amount: 150 }
];
var totalAmount = _.sumBy(orders, 'amount');
console.log(totalAmount);

You can also try this code with Online Javascript Compiler
Run Code
Output:
450
Shows the use of property name shorthand for summing order amounts.
Calculating Total in Data Analysis:
JavaScript
var salesData = [
{ month: 'January', sales: 80 },
{ month: 'February', sales: 120 },
{ month: 'March', sales: 100 }
];
var totalSales = _.sumBy(salesData, 'sales');
console.log('Total Sales:', totalSales);

You can also try this code with Online Javascript Compiler
Run Code
Output:
'Total Sales: 300'
An example of using _.sumBy() in data analysis to calculate total sales.
Complex Structures Summation:
JavaScript
var measurements = [
{ item: 'Item1', dimensions: { length: 10, width: 5 }},
{ item: 'Item2', dimensions: { length: 15, width: 10 }}
];
var totalLength = _.sumBy(measurements, item => item.dimensions.length);
console.log('Total Length:', totalLength);

You can also try this code with Online Javascript Compiler
Run Code
Output:
'Total Length: 25'
Demonstrates calculating the total length from a complex data structure.
Frequently Asked Questions
How does _.sumBy() handle non-numeric values?
_.sumBy() ignores non-numeric values when calculating the total. If the iteratee function returns non-numeric values, they may affect the calculation, leading to unexpected results or NaN.
What happens if the array is empty or the property is missing?
If the array is empty or the specified property does not exist on any object in the array, _.sumBy() returns 0.
Can _.sumBy() be used with arrays of simple values?
For arrays of simple values (like numbers), _.sum() is more suitable. _.sumBy() is specifically designed for arrays of objects.
Conclusion
Lodash's _.sumBy() method is a valuable tool for calculating the sum of a specific property in an array of objects. It provides a concise and effective solution for financial computations, inventory management, and data analysis involving complex data structures.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.