Photo of a vintage calculator

How to sum the elements of an Array in JavaScript?

You have a variety of options at your disposal to perform addition on numbers from an array. I present to you the 5 most common solutions, of which using Array.reduce is the best option πŸ†.

Array.reduce to sum numbers from an array

If you just want the solution right away, you can find it in the code snippet below. If you want to understand how the code actually works, keep reading.

const array = [5, 10, 2];

const sum = array.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);

console.log(sum); // πŸ‘‰οΈ 17

// same as above, but more concise, one-liner
const sum2 = array.reduce((acc, curr) => acc + curr, 0);

To get the sum of an array of numbers, use the Array.reduce method. This method allows you to take all the elements of an array, apply a function to each of them, and accumulate the result in an return value.

The reducer function can take up to four arguments, but to sum an array of numbers, you only need the first two:

  • accumulator, also referred to as previous value
  • current value

If you would like to learn more about how to use the reduce method, see our article How to use reduce in Javascript? [5 EXAMPLES].

Array.reduce simplified syntax

// Callback function
reduce(function(accumulator, currentValue) { /* ... */ },  initialValue)

// Callback function in arrow function style
reduce((accumulator, currentValue) => { /* ... */ }, initialValue)

callback: is a function that is passed as the first parameter to the reduce method. In turn, this function receives 2 parameters: the previous value and the current value. reduce will loop through all the elements of the array and apply the callback function.

The previous value will be the result returned by the previous callback execution. The first time the callback function executes, previousValue will point to the initialValue. The current value will point to the current element.

initialValue: The value reduce will pass to the callback function as the previousValue the first time it is executed. This value is optional and if it is not specified, previousValue will point to the first item in the array, and callback starts executing with the second value in the array as currentValue.

This may sound a bit complicated, but an example will help you understand the concept more clearly. First, let’s see how to perform sum elements of an array of numbers.

const array = [5, 10, 2];

const sum = array.reduce((previousValue, currentValue) => {
  return previousValue + currentValue;
}, 0);

console.log(sum); // πŸ‘‰οΈ 17

The callback function was called 3 times, with the arguments and return values as shown below:

previousValuecurrentValuereturns
first055
second51015
third15217

Array.reduce to sum a property value in an array of objects

In the following example we will see how to sum a property in an array of objects using the Array.reduce method. The code is similar to when we sum an array of integers, the difference is that we use a property of the object in our addition.

const products = [
  { name: 'Chess Set', price: 10.50 },
  { name: 'Design Patterns Book', price: 15.00 },
  { name: 'Desk Lamp', price: 20.25 },
];

const sum1 = products.reduce((previous, current) => {
  return previous + current.price; // sum the property's value
}, 0);

console.log(sum); // πŸ‘‰οΈ 45.75

// same as above, but more concise, one-liner
const sum2 = products.reduce((prev, curr) => prev + curr.price, 0);

for…of loop

The for…of loop allows us to iterate over an array. To get the total from an array of integers, follow these three simple steps:

  1. Declare a variable (in the example it is sum) and assign it the value of 0.
  2. Use for...of to iterate over the array.
  3. On each iteration, reassign the variable sum to the value of its current value plus the value of the current element (sum += value)

⚠️ Notice that we declare the variable sum using the let keyword. If we had used const, we would not have been able to reassign the value.

const arr = [2, 4, 14];

let sum = 0;

for (const value of arr) {
  sum += value;
}

console.log(sum); // πŸ‘‰οΈ 20

Classic for loop

You can also use the classic for loop to add an array of numbers.

⚠️ Notice that we declare the variable sum using the let keyword. If we had used const, we would not have been able to reassign the value.

const arr = [2, 4, 14];

let sum = 0;

for (let index = 0; index < arr.length; index++) {
  sum += arr[index];
}

console.log(sum); // πŸ‘‰οΈ 20

lodash sum method to sum an array of numbers

If you already have the lodash utility library installed you can easily add the numbers present in an array with the sum method.

const _ = require('lodash');

const sum = _.sum([2, 4, 14]);

console.log(sum); // πŸ‘‰οΈ 20

lodash sumBy method to sum property values in an array of objects

const products = [
  { name: 'Juego de Ajedrez', price: 10.50 },
  { name: 'Libro Design Patterns', price: 15.00 },
  { name: 'Lampara de escritorio', price: 20.25 },
];

const sum = _.sumBy(products, (product) => product.price);

console.log(sum); // πŸ‘‰οΈ 45.75

sumBy is similar to sum but also accepts a function that is called by each item of the array to provide the value to be added.

Array.reduce does not return the expected result ❌

Can you spot the issue in the code below? πŸ‘€

const numbers = ['5', '10'];

// returns '0510' ❌
const total = numbers.reduce(
  (prev, curr) => prev + current, 
  0
);

Pay close attention to the elements of the array. The numbers are in quotes, which causes them to be interpreted as strings. Instead of adding 5 + 10, what you are doing is string concatenation.

To fix it you could cast the values via the Number object.

const numbers = ['5', '10'];

// returns 15 βœ…
const total = numbers.reduce(
  (prev, curr) => Number(prev) + Number(curr), 
  0
);

Similar Posts