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.
Basic Usage to Find Sum:
4.2.
JavaScript
4.3.
Summing Values in a Data Set:
4.4.
JavaScript
4.5.
Application in Financial Calculations:
4.6.
JavaScript
4.7.
Using with Complex Data Structures:
4.8.
JavaScript
5.
Frequently Asked Questions
5.1.
How does _.sum() handle non-numeric values in the array?
5.2.
Can _.sum() be used with large data sets?
5.3.
Is _.sum() the best choice for all summation needs?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.sum() Method

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Summing an array of numbers is a fundamental operation in many programming tasks, especially in data processing and analysis. Lodash, a widely-used JavaScript utility library, simplifies this task with the _.sum() method. 

Lodash _.sum() Method

This method efficiently calculates the sum of the numbers in an array, making it invaluable for tasks involving numerical computations.

Why This Function is Used

The _.sum() function is used to calculate the total of an array of numbers. It provides a concise and readable way to perform this summation, enhancing code clarity. This is particularly useful in scenarios involving statistical calculations, aggregations, or whenever you need to quickly compute the total of a series of numbers.

Syntax, Parameter and Return Value

Syntax: 

_.sum(array)

Parameters:

array (Array): The array of numbers to sum up.

Return Value: 

(Number) - Returns the sum of the array.

Examples 

Basic Usage to Find Sum:

  • JavaScript

JavaScript

var _ = require('lodash');

console.log(_.sum([4, 2, 8, 6]));
You can also try this code with Online Javascript Compiler
Run Code

Output: 

20


Demonstrates finding the sum of numbers in a simple array.

Summing Values in a Data Set:

  • JavaScript

JavaScript

var expenses = [200, 150, 50, 100];

var totalExpenses = _.sum(expenses);

console.log('Total Expenses:', totalExpenses);
You can also try this code with Online Javascript Compiler
Run Code

Output: 

'Total Expenses: 500'


Shows how to sum up values in an array representing expenses.

Application in Financial Calculations:

  • JavaScript

JavaScript

var prices = [19.99, 45.50, 23.75];

var totalPrice = _.sum(prices);

console.log('Total Price:', totalPrice);
You can also try this code with Online Javascript Compiler
Run Code

Output: 

'Total Price: 89.24'


An example of using _.sum() to calculate the total price of items.

Using with Complex Data Structures:

  • JavaScript

JavaScript

var orders = [

 { id: 1, quantity: 2 },

 { id: 2, quantity: 5 },

 { id: 3, quantity: 3 }

];

var totalQuantity = _.sum(_.map(orders, 'quantity'));

console.log('Total Quantity:', totalQuantity);
You can also try this code with Online Javascript Compiler
Run Code

Output:

'Total Quantity: 10'


Demonstrates calculating the total quantity of orders from an array of objects using Lodash’s _.map().

Frequently Asked Questions

How does _.sum() handle non-numeric values in the array?

_.sum() ignores non-numeric values when calculating the total. However, the presence of such values may affect the calculation, leading to unexpected results.

Can _.sum() be used with large data sets?

Yes, _.sum() can be used with large data sets. However, for extremely large arrays, consider performance implications as the entire array needs to be iterated over.

Is _.sum() the best choice for all summation needs?

_.sum() is suitable for basic summation calculations. For complex summations, like conditional or weighted sums, other Lodash methods or custom functions might be more appropriate.

Conclusion

Lodash's _.sum() method provides a simple and efficient way to calculate the sum of numerical values in an array. It enhances code readability and is particularly useful compared to more verbose native JavaScript approaches in certain scenarios.

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.

Live masterclass