calculate sum of array in js

How to Find Sum of Array of Numbers in JavaScript

JavaScript arrays are powerful data structures that allow you to not only store lots of data in a compact manner but also support a wide range of functions to play with their elements. In some cases, you may need to simply calculate sum of array of numbers in JavaScript. One of the simplest approach is to loop through the array items one by one and keep adding each item to the sum. But this is a very tedious and time consuming approach. As JavaScript develops, it offers newer and efficient ways to get sum of array items. In this article, we will learn how to find sum of array of numbers in JavaScript.


How to Find Sum of Array of Numbers in JavaScript

Let us say you have the following JS array.

[1, 2, 3];

You can easily sum up the items of above array using reduce() function in JS. It allows you to iterate through array items, perform operation on each item, store the result of each iteration and use each item to modify the previously stored result.

So we use reduce() function to loop through the array items, add each item to the sum one by one to get the total sum.

sum = [1, 2, 3].reduce((partialSum, a) => partialSum + a, 0);
console.log(sum); // 6

In the above approach, we have not assigned a default sum value which may give error in some cases. For example, you may get a TypeError if the array is empty. Here is an example where we set default sum value to be zero.

[1, 2, 3, 4].reduce((a, b) => a + b, 0)

In the above code, the 2nd argument of reduce() function is 0, the default value. The first argument is the operation to be performed for each iteration. So we set the default sum to be zero, iterate through array items, add current item to the sum of previous items.

Sometimes, you may have non numerical values in array as shown below.

 ["hi", 1, 2, "joe"]

In the above case, we need to be able to skip non number items while calculating the sum. Here is how you can do this. We define a function that basically checks if an input is number or not.

function numOr0(n){
   return isNaN(n) ? 0 : n;
}

The above function checks if an input is number or not. If it is a number, it returns the number as it is, else it returns 0. We use that function in our reduce function()

console.log(
  ["hi", 1, 2, "joe"].reduce((a, b) => 
    numOr0(a) + numOr0(b))
)
//output is 3

In the above reduce() function, we check if each number is 0 or not and then add them to the sum of previous items.

We also specify a default sum value, to avoid TypeError, and get a final JS code as shown below.

["hi", 1, 2, "joe"].reduce((a, b) =>      numOr0(a) + numOr0(b), 0)

If you are have an array variable test_array, you can replace it in above command as shown below.

test_array.reduce((a, b) =>      numOr0(a) + numOr0(b), 0)

In this article, we have learnt several ways to get sum of array of numbers using JavaScript.

Also read:

Remove Unicode Characters from String
Remove Accents/Diatrics from String in Python
Remove Accents/Diatrics from String in JavaScript
How to Convert Array to Object in JavaScript
How to Test for Empty JavaScript Object

Leave a Reply

Your email address will not be published. Required fields are marked *