Last updated: Mar 2, 2024
Reading timeยท5 min
To get the sum of an array of numbers:
Array.reduce()
method to iterate over the array.reduce
method to 0
.const arr = [5, 15, 45]; const sum = arr.reduce((accumulator, value) => { return accumulator + value; }, 0); console.log(sum); // ๐๏ธ 65
The function we passed to the Array.reduce() method gets called for each element in the array.
We initialized the accumulator
variable to 0
because that's what we passed
as the second argument to the reduce()
method.
accumulator
and the current array element.After the last iteration, the sum
variable stores the sum of the numbers in
the array.
If you have to calculate the sum of arrays often, define a reusable function.
function calculateSum(array) { return array.reduce((accumulator, value) => { return accumulator + value; }, 0); } const result1 = calculateSum([1, 2, 3]); console.log(result1); // ๐๏ธ 6 const result2 = calculateSum([1, 2, 3, 4]); console.log(result2); // ๐๏ธ 10
The calculateSum()
function takes an array as a parameter and calculates the
sum of the numbers in the array.
You can also shorten the function we passed to the reduce()
method by using an
implicit return statement.
function calculateSum(array) { return array.reduce((accumulator, value) => accumulator + value, 0); } const result1 = calculateSum([1, 2, 3]); console.log(result1); // ๐๏ธ 6 const result2 = calculateSum([1, 2, 3, 4]); console.log(result2); // ๐๏ธ 10
The arrow function in the example uses an implicit return.
An alternative and perhaps simpler approach is to use a for...of
loop.
for...of
loopThis is a three-step process:
sum
variable and initialize it to 0
.for...of
loop to iterate over the array.sum
variable to its current value plus the
value of the current element.const arr = [5, 15, 45]; let sum = 0; for (const value of arr) { sum += value; } console.log(sum); // ๐๏ธ 65
If you need to handle non-numeric values, use the typeof
operator.
// ๐๏ธ array contains non-numeric values const arr = ['a', 5, 'b', 15, 'c', 45]; let sum = 0; for (const value of arr) { if (typeof value === 'number') { sum += value; } } console.log(sum); // ๐๏ธ 65
The array in the code sample also contains non-numeric values, so we used the
typeof
operator to
check if each value is a number
before adding it to the total.
The for...of statement is
used to loop over iterable objects like arrays, strings, Map
, Set
and
NodeList
objects and generators
.
sum
variable using the let
keyword. Had we declared the variable using const
, we wouldn't be able to reassign it.On each iteration, we reassign the sum
variable to its current value plus the
value of the current element.
If you have to do this often, extract the logic into a reusable function.
function calculateSum(array) { let total = 0; for (const value of array) { total += value; } return total; } const result1 = calculateSum([1, 2, 3]); console.log(result1); // ๐๏ธ 6 const result2 = calculateSum([1, 2, 3, 4]); console.log(result2); // ๐๏ธ 10
The calculateSum()
function takes an array as a parameter, calculates the sum
of its values and returns the result.
Alternatively, you can use Array.forEach()
.
Array.forEach()
This is a three-step process:
sum
variable and initialize it to 0
.Array.forEach()
method to iterate over the array.const arr = [5, 15, 45]; let sum = 0; arr.forEach(value => { sum += value; }); console.log(sum); // ๐๏ธ 65
The function we passed to the Array.forEach() method gets called with each element in the array.
sum
variable to its current value plus the value of the current array element.The sum
variable stores the sum of the values in the array after the last
iteration.
If you have to calculate the sum of an array's elements often, define a reusable function.
function calculateSum(array) { let total = 0; array.forEach(value => { total += value; }); return total; } const result1 = calculateSum([1, 2, 3]); console.log(result1); // ๐๏ธ 6 const result2 = calculateSum([1, 2, 3, 4]); console.log(result2); // ๐๏ธ 10
The calculateSum()
function takes an array as a parameter, calculates the sum
of the array's elements and returns the result.
Alternatively, you can use a basic for
loop.
for
loopThis is a three-step process:
sum
variable and initialize it to 0
.for
loop to iterate over the array.sum
variable to its current value plus the
current array element.const arr = [5, 15, 45]; let sum = 0; for (let index = 0; index < arr.length; index++) { sum += arr[index]; } console.log(sum); // ๐๏ธ 65
We used a basic for
loop to iterate over the array.
On each iteration, we use the index to access the current array element and
reassign the sum
variable.
Which approach you pick is a matter of personal preference. I'd use the
Array.reduce()
method or a for...of
loop as both options are quite direct
and intuitive.
while
loopYou can also use a while
loop to get the sum of an array of numbers.
const arr = [5, 15, 45]; let sum = 0; let i = -1; while (++i < arr.length) { sum += arr[i]; } console.log(sum); // ๐๏ธ 65
We initialized the sum
and i
variables using the let
keyword.
Using let
is important because variables declared using const
cannot be
reassigned.
On each iteration of the while
loop, we increment the i
variable and add the
current array element to the total.
lodash
If you use the lodash
library, you can also use the lodash.sum()
method to
get the sum of an array of numbers.
import _ from 'lodash'; console.log(_.sum([1, 2, 3])); // ๐๏ธ 6 console.log(_.sum([10, 20, 30])); // ๐๏ธ 60
If you need to install lodash
, run the following command.
# ๐๏ธ initialize a package.json file if you don't have one npm init -y npm install lodash
The lodash.sum() method takes an array as a parameter and computes the sum of the values in the array.
You can learn more about the related topics by checking out the following tutorials: