How to Get Sum of Array in JavaScript

0
471
Javascript Sum Array - How to Find Sum of Array in JS

How can you find the sum of its elements? Well, the solution is an array.reduce() method.

Javascript sum array

To get a sum array in JavaScript, use the array.reduce() method. Array.prototype.reduce() function can be used to iterate through an array, adding the current element value to the sum of the previous item values.

The reduce() method reduces an array to a single value. The reduce() function executes the provided function for each array value (from left to right). The return value of a method is stored in an accumulator (result/total).

Syntax

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

Parameters

The total argument is required. It is the initial value or the previously returned value of the function.

CurrentValue is the required argument. It is the value of the current element in an array.

The currentIndex is an optional argument. It is the index of the current element.

The arr is an optional argument. It is the array object the current element belongs to.

The initialValue is an optional argument. It is a value to be passed to the function as the initial value.

The first time the callback is called total, and currentValue can be one of two values. If an initialValue is provided in the call to the reduce() method, the total will be equal to the initialValue, and the currentValue will be similar to the first value in the array.

If no initialValue is provided, the total will equal the first item in the array, and the currentValue will be similar to the second.

Example

Let’s define an array with five values and then find the sum of the array using the array.reduce() method.

// app.js

let data = [11, 21, 46, 19, 18];

sum = data.reduce((a, b) => {
  return a + b;
});

console.log('The sum is: ', sum);

Output

The sum is:  115

That is it. We go the sum of all the integers of the array.

What it does behind the scene is that in the first case, the initial value is 0, and the first element is 11. So, 11 + 0 = 11.

In the second loop, our old value is 11, and the next value is 21. So, 11 + 21 = 32. In the next cycle, our old value is 32, and the next value is 46. So, 46 + 32 = 78.

In the third cycle, our old value is 78, and the new value is 19. So, 78 + 19 = 97.

In the last loop, our old value is 97, and the next is 18, so 97 + 18 = 115.

So, this is how it sums up all the elements of the array.

In this example, we have not defined an initial value, but you can determine an initial value, and it will take as the first old value, and then it will start adding the next values in the array.

That’s it.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.