Get the sum of all numbers in a JavaScript array with the reduce method


There are many ways to get the sum of all numbers in an array. I find that using the reduce() method is the most elegant way to perform this simple task.

Getting the sum

To get the sum of all the numers in our array, we add each value val with the accumulated result of each former addition acc.

const myArray = [1, 2, 3, 4, 5, 6];

const newArr = myArray.reduce((acc, val) => {
return acc + val;
})

console.log(newArr) // 21

A leaner function

We can also reduce the function to a single line and remove the return statement altogether. This might be less readable for some, but I enjoy the aesthetics of a single declaration.

const newArr = myArray.reduce((acc, val) => return acc + val)

Numbers as strings

Here is a small bonus someone requested. If your array has both numbers as strings and number values, we can wrap the val in the parseInt() method, converting the string to a number type, before adding it the the accumulated value acc.

const myArray = [1, '2', 3, 4, 5, '6'];

const newArr = myArray.reduce((acc, val) => {
return acc + parseInt(val, 10);
})

console.log(newArr) // 21

That is it! once you get your head around reduce(), your life will be better, I guarantee it.