Categories
JavaScript Answers

How to Find the Sum of an Array of Numbers with JavaScript?

Spread the love

Finding a sum of an array of numbers is something that we’ve to do a lot in our JavaScript apps.

In this article, we’ll look at how to find the sum of an array of numbers with JavaScript.

Array.prototype.reduce

The JavaScript array’s reduce method lets us get numbers from an array and add them up easily.

To do this, we write:

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

We call reduce with a callback to help us add up the numbers.

a is the accumulated result, which is the partial sum.

And b is the item that we’re iterating through.

In the 2nd argument, we pass in 0 to set the initial result of a .

Therefore, sum is 10.

Lodash sum Method

Lodash has the sum method that is specially made to add up numbers in an array together.

For instance, we can write:

const array = [1, 2, 3, 4];
const sum = _.sum(array);
console.log(sum)

to call sum with the array number array.

Loop

We can use a for-of loop to loop through an array of numbers and add them up.

For instance, we can write:

const array = [1, 2, 3, 4];
let sum = 0
for (const a of array) {
  sum += a
}
console.log(sum)

We get number a from array and add them to sum .

Also, we can use a while loop to loop through the number array.

To do this, we write:

const array = [1, 2, 3, 4];
let sum = 0
let i = 0;
while (i < array.length) {
  sum += array[i];
  i++
}
console.log(sum)

Array.prototype.forEach

We can also use the forEach method to loop through the number array and add up all the numbers.

For example, we can write:

const array = [1, 2, 3, 4];
let sum = 0
array.forEach(a => {
  sum += a;
});
console.log(sum)

We call forEach with a callback.

Then in the callback, we get the value that’s being iterated through with the first parameter.

Then we add that value to the sum .

Conclusion

There’re several ways we can use to find the sum of the numbers in a number array with JavaScript.

One way is to use the reduce method.

Other ways include using the for-of loop, while loop, or forEach to loop through an array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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