By Payal Udhani
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.
Web development, programming languages, Software testing & others
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.
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.
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.
- 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.
- 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.
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.
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.
<!DOCTYPE html> <html> <body> <p>Demostration of using Array.prototype.reduce() method for calculationg sum of array elements</p> <p ></p> <script> // sums to 1015 let valueInBeginning = 0; let totalExpenditure = [
We can find the total expenditure by using the reduced function as shown above by considering the element. expenditure value.
Get Educative’s popular interview prep course for free.
First, we’ll use the traditional for loop. Secondly, we’ll use forEach , an array-like method, and lastly, we’ll make use of for. of .
In this shot, our array example is [1, 4, 0, 9, -3] , and the expected output is 11 .
1. Using the traditional for loop
In this method, you iterate and add each item until you reach the last item.
How to find the sum of an array of numbers
I thought $.each might be useful, but I’m not sure how to implement it.
59 Answers 59
This’d be exactly the job for reduce .
If you’re using ECMAScript 2015 (aka ECMAScript 6):
Isn’t that pretty? 🙂
Recommended (reduce with default value)
Array.prototype.reduce can be used to iterate through the array, adding the current element value to the sum of the previous element values.
Without default value
You get a TypeError
Prior to ES6’s arrow functions
If non-numbers are possible inputs, you may want to handle that?
Non-recommended dangerous eval use
Of course displaying an alert isn’t the worst thing that could happen. The only reason I have included this is as an answer Ortund’s question as I do not think it was clarified.
Why not reduce? It’s usually a bit counter intuitive, but using it to find a sum is pretty straightforward:
Anyone looking for a functional oneliner like me?
Here’s the oneliner for modern JS:
(If you happen to have to support ye olde IE without arrow functions:)
Note that 0 is the initial value here, so you can use that as offset if needed. Also note that this initial value is needed, otherwise calling the function with an empty array will error.
If you happen to be using Lodash you can use the sum function
This is possible by looping over all items, and adding them on each iteration to a sum -variable.
The same as above, however annotated and prepared as a simple function:
OK, imagine you have this array below:
Let’s start looking into many different ways to do it as I couldn’t find any comprehensive answer here:
1) Using built-in reduce()
2) Using for loop
3) Using while loop
4) Using array forEach
and call it like this:
It’s not recommended to prototype something like this to Array.
You can also use reduceRight.
which results output as 21.
You can try the following code:
This works for me (the result should be 5). I hope there is no hidden disadvantage in this kind of solution.
Basically, I wanted to contribute this because I didn’t see many solutions that don’t use built-in functions, and this method is easy to write and understand.
If you care about performance, define a function that uses a for -loop.
I benchmarked a selection of implementations using benchmark.js (typescript version):
In chrome 104, the for -loop-based implementations are the fastest:
Firefox 104 shows similar behaviour:
Implementations defining an anonymous function are generally slower because creating an anonymous function is a significant overhead. When running the benchmark with a large array, e.g., with length 1000 instead of 100, the difference between reduce and the for -loop-based implementations becomes insignificant in chrome.
Chrome’s V8 engine knows how to inline simple anonymous functions in reduce since the reduce test case is much faster than the predefined reduce test case. Firefox seems to try something similar but is less efficient in doing so. Non-inlined function calls are pretty slow in js since the call stack is less efficient than the call stack in compiled software.
Similar to reduce , the forEach — and jquery -based implementations use anonymous functions and are relatively slow. lodash has a specialized sum implementation, but it is (as of v4.0.0) implemented as a special case of sumBy , which is relatively inefficient.
eval is the by far slowest test case. This makes sense since constructing the string using concatenations might cause several dynamic allocations (which are slow). Next, the parser has to be invoked and only then can the code be finally executed.
I’ve included some recursive implementations because some people on the internet claim that recursion is faster than loops in js. I can’t reproduce their example — using benchmark.js , recursion is very slow, and when using console.time with a loop, both functions take the same time. When calculating the sum, as expected, recursion is much slower than loops, probably due to intense usage of the js call stack.
The naive implementation would be manually adding all 100 elements of the array. While being quite inconvenient, this is the fastest implementation. But, luckily, for -loops come very close. Adding a single function call around the loop doesn’t harm the performance. Therefore, you can feel free to use the utility function from above.
I have no explanation why the while loop is slower than the for loop. Iterating the array in reverse doesn’t seem to be the problem here.
1. Использование Array.prototype.reduce() функция
The reduce() можно использовать для выполнения функции редуктора для каждого элемента массива. Чтобы вычислить сумму всех значений массива, функция редуктора должна добавить текущее значение элемента к уже вычисленной сумме предыдущих значений.
Подводя итог, значения, содержащиеся в массиве, вы должны указать значение по умолчанию для reduce() метод, иначе код выдаст TypeError на пустой массив. Это показано ниже с использованием анонимной функции.