;

How to Find the Sum of an Array of Numbers in Javascript


Tutorialsrack 15/01/2022 Jquery Javascript

In this article, you will learn how to find the sum of an array of numbers in Javascript. There are various ways to find the sum of an array of numbers in Javascript. You can find the sum of an array of numbers using reduce() method, loops(for loop, forEach loop) or lodash library. Let’s discuss each of them and try examples:

Example 1: Using reduce() Method

The reduce() method executes a user-supplied “reducer” callback function on each element of the array, in order, pass in the return value from the calculation on the preceding element and it returns a single value.

let arr = [5, 10, 15, 20];
let sum = arr.reduce(function (a, b) {
  return a + b;
}, 0); // with initial value to avoid when the array is empty

console.log(sum); // Output: 50

Even better! If you use ES2015, you can use reduce() function like this:

const sum = [5, 10, 15, 20].reduce((a, b) => a + b,0); // with initial value to avoid when the array is empty

console.log(sum); // Output: 50

Example 2: Using for Loop

The for loop is used to iterate an array. You can use it to add all the numbers in an array and store it in a variable.

const array = [5, 10, 15, 20];
let sum = 0;

for (let i = 0; i < array.length; i++) {
    sum += array[i];
}
console.log(sum); // Output = 50

Example 3: Using forEach loop

Another way of calculating the sum of an array of numbers is using a forEach loop.

const array = [5, 10, 15, 20];
let sum = 0;

array.forEach(number => {
  sum += number;
})

console.log(sum); // Output = 50

Example 4: Using Lodash Library

One another way of calculating the sum of an array of numbers using  _.sum(array)

Include the Lodash Library in your code:

<script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script>

Calculating the sum of the values in the array.

const array = [5, 10, 15, 20];
let sum = _.sum(array);
 
console.log(sum); // Output = 50

I hope this article will help you to understand how to find the sum of an array of numbers in Javascript.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags