Updated April 13, 2023
Introduction to Javascript Sum Array
In javascript, we can calculate the sum of the elements of the array by using the Array.prototype.reduce() method. The reduced method for arrays in javascript helps us specify a function called reducer function that gets called for each of the elements of an array for which we are calling that function. The output of the reduce() method is a single value that is returned as a collection of all the operations performed on each of the element of the array that is defined in the reducer function. We can use the reduce() function to retrieve the sum of all the array elements by writing a corresponding reducer function that will add the elements of the array and call this reducer function inside the reduce method.
In this article, we will learn about how sum of array elements can be calculated using the standard old way of for loop and then by the new optimized, efficient and convenient way of reducing () method along with its syntax and examples.
Old Way of the Calculating Sum of Array Elements
Before the introduction of the reduce() method, we used to calculate the sum of array elements using the for a loop. We would iterate the loop from 0 to the length of the array as indexing of the array starts from 0 and then calculate the sum inside the for a loop. Let us consider one example where we will calculate the total salary of all the employees where the salary of each employee is stored in the array salaries as shown below.
Code:
<!DOCTYPE html>
<html>
<body>
<p>Demonstration of using the old way of for loop for calculating sum of array elements</p>
<p id="demo"></p>
<script>
var salaries = [10000, 20000, 30000, 40000] // sums to 100000
var totalSalary = 0;
for (var i = 0; i < salaries.length; i++) {
totalSalary += salaries[i]
}
document.getElementById("demo").innerHTML = totalSalary;
</script>
</body>
</html>
that gives the following output after execution:
We can see how the totalSalary variable is added with each of the value of the elements of the salaries array by iterating the for loop to retrieve the sum of the array elements that is the total salary of all the employees.
Array.prototype.reduce() Method
Now, we will learn about the reduce() method that will be used for calculating the sum of the array elements. Let us begin by studying its syntax.
array.reduce(callback( accumVariable, curValue[, index[, yourArray]] )[, valueInBeginning])
- callback – It is also called the reducer function that is a callback or function that executes for each of the elements of the array. Note that the first value in the array is not considered if we do not supply any initial value in the valueInBeginning parameter.
- accumVariable – It is the variable that stores the result to be returned after the reducer function is executed for all of the elements of the array. It has the value that was returned at the time of the last invocation of the reduce() method or the valueInBeginning parameter value if specified. This is the required parameter to the callback function and needs to be mentioned while using it.
- curValue – It is a required parameter of the reducer function callback and stands for the current element of the array for which the reducer function is being executed.
- Index – It is the index of the current element that is being processed and for which the reducer function is getting executed. It has the initial value as zero if valueInBeginning is specified else has 1 value as the initial value in it. It is optional.
- yourArray – This is the array for which the reducer function needs to be called for each of its elements. It is an optional parameter.
- valueInBeginning – It is the initial value that is the value that will be used as the first parameter to the function. If not specified, then the first element of the array at the zero indexes will be used as the accumulator value in the beginning and the value of the first element of the array will be skipped for the curValue variable. If the reduce method is called using the empty brackets without any parameters for a blank array without specifying the value in beginning i.e initial value then javascript will throw a TypeError.
- Return value – The value that is returned by the reducer function/callback is a single value that is the result of the accumulation of all the values that were resulted by executing the reducer function for each of the elements of the array.
Example
Let us consider a simple example of a previous scenario where we wanted to calculate the total salary of all the employees stored in the array format. But now, we will use the reduce() method to calculate the sum instead pf for a loop as shown below.
Code:
<!DOCTYPE html>
<html>
<body>
<p>Demonstration of using Array.prototype.reduce() method for calculating sum of array elements</p>
<p id="demo"></p>
<script>
// sums to 100000
let totalSalary = [10000, 20000, 30000, 40000].reduce(function (accumVariable, curValue) {
return accumVariable + curValue
}, 0);
document.getElementById("demo").innerHTML = totalSalary;
</script>
</body>
</html>
that gives the following output after execution:
Let us consider one more example where we will calculate the total expenditure where values in the array are stored in key-value pair where the key is the expenditure as shown below.
Code:
<!DOCTYPE html>
<html>
<body>
<p>Demostration of using Array.prototype.reduce() method for calculationg sum of array elements</p>
<p id="demo"></p>
<script>
// sums to 1015
let valueInBeginning = 0;
let totalExpenditure = [{expenditure: 210}, {expenditure: 152}, {expenditure: 653}].reduce(
(accumVariable, curValue) => accumVariable + curValue.expenditure
, valueInBeginning
)
document.getElementById("demo").innerHTML = "Total Expenditure = " + totalExpenditure;
</script>
</body>
</html>
that gives the following output after execution:
We can find the total expenditure by using the reduced function as shown above by considering the element. expenditure value.
Conclusion
We can calculate the sum of the array elements by using the standard for loop. The most recent, optimized, and efficient way of calculating the sum of array elements is the use the reduce() method in javascript and write a reducer function or callback for it that will return the accumulated value.
Recommended Articles
This is a guide to Javascript Sum Array. Here we discuss the Introduction, Array.prototype.reduce() Method, and Old Way of the Calculating Sum of Array Elements with examples. You may also have a look at the following articles to learn more –