How to Find the Sum of an Array of Numbers
There are multiple ways that you should use in order to calculate the sum of an array of numbers. Let’s discuss each of them and try examples.
You can use the reduce() method to find the sum of an array of numbers.
The reduce() method executes the specified reducer function on each member of the array resulting in a single output value as in the following example:
The 0 in is the default value. If default value is not supplied, the first element in the array will be used. If the array is empty, you will get an error.
If you use ES2015, you can make it more verbose like this:
Another fast method is using for loop which is even faster as the reduce() method:
An alternative way of calculating the array of numbers is using forEach loop like this:
How to add only certain elements of an array?
In this example, we define an array of 10 numbers and then use a
for loop to iterate over the elements with indices 3-7 (which is the fourth through eighth elements of the array). The loop adds up each element to a running total stored in the
After the loop completes, we have the sum of the elements with indices 3-7 stored in the
sum variable, which we log to the console.
You can adjust the starting and ending indices in the loop to add up different ranges of elements in the array.
The reduce() method
The reduce() method invokes a reducer function provided on each element of the array and results in single output value. It executes the callback once for each assigned value present in the array taking four arguments: accumulator, currentValue, currentIndex, array. It is recommended to provide default value such as 0 for performing addition and 1 for performing multiplication.