How to find the sum of an array of numbers

Created by Florian MargaineLinked to 62.2m issues across 234 teams

tl;dr

Here's how to find the sum of an array of numbers using the reduce method.

First, you need to create an array of numbers. For example, let's say you have an array of numbers [1, 2, 3].

Next, you need to use the reduce method to calculate the sum of the array. If you are using ECMAScript 2015 (also known as ECMAScript 6), you can use the following code:

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

If you are using an older version of JavaScript, you can use the following code:

const sum = [1, 2, 3].reduce(add, 0); // with initial value to avoid when the array is empty function add(accumulator, a) { return accumulator + a; } console.log(sum); // 6

And that's it! You have now successfully calculated the sum of an array of numbers.