Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Why This Function is Used
3.
Syntax, Parameter and Return Value
3.1.
Syntax: 
3.2.
Parameters:
3.3.
Return Value:
4.
Examples 
4.1.
Summing a Specific Property:
4.2.
JavaScript
4.3.
Using Property Name Shorthand:
4.4.
JavaScript
4.5.
Calculating Total in Data Analysis:
4.6.
JavaScript
4.7.
Complex Structures Summation:
4.8.
JavaScript
5.
Frequently Asked Questions
5.1.
How does _.sumBy() handle non-numeric values?
5.2.
What happens if the array is empty or the property is missing?
5.3.
Can _.sumBy() be used with arrays of simple values?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.sumBy() Method

Author Pallavi singh
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

In data processing, especially when working with arrays of objects, calculating the sum of a specific property is a frequent requirement. Lodash's _.sumBy() method streamlines this process, allowing for the computation of the sum of a property in an array of objects based on a specific iterate function. 

Lodash _.sumBy() Method

This method is highly useful in scenarios where you need to calculate totals from complex data structures.

Why This Function is Used

The _.sumBy() function is used to calculate the total of a specific property in an array of objects. Unlike the basic _.sum() function, which calculates the sum of an array of numbers, _.sumBy() is designed to work with collections of objects where the target value for the summation is a property of these objects. This method simplifies extracting and summing these values, making it highly useful in financial calculations, inventory management, and statistical computations.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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

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);

Output: 

9


Demonstrates calculating the total quantity of products.

Using Property Name Shorthand:

  • JavaScript

JavaScript

var orders = [

 { id: 1, amount: 100 },

 { id: 2, amount: 200 },

 { id: 3, amount: 150 }

];

var totalAmount = _.sumBy(orders, 'amount');

console.log(totalAmount);

Output:

450


Shows the use of property name shorthand for summing order amounts.

Calculating Total in Data Analysis:

  • JavaScript

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);

Output: 

'Total Sales: 300'


An example of using _.sumBy() in data analysis to calculate total sales.

Complex Structures Summation:

  • JavaScript

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);

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 DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Lodash _.maxBy() Method
Next article
Lodash _.minBy() Method
Live masterclass