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
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
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
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
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 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.