There are three methods to calculate the sum an average of elements in an array in JavaScript.
Quick Answer: const sum = myArray.reduce((a, b) => a + b, 0); const average = (sum / myArray.length) || 0;
Basic Example
var myArray = [ 0, 1, 2, 3, 4, 5, ];
const sum = myArray.reduce((a, b) => a + b, 0);
const average = (sum / myArray.length) || 0;
console.log(`The sum is: ${sum}. The average is: ${average}.`); //"The sum is: 15. The average is 2.5."
This tutorial teaches you how to calculate the sum and average of elements in an array in JavaScript.
Using Reduce [ES6]
The reduce() method executes a user-defined reducer callback function on each element of the array.
To sum the array of numbers using the reduce()
method:
- Pass the
a+b
as the user-defined function - Pass
0
as the initial value to the accumulator
The array must not have undefined
items while using the reduce()
method.
To calculate the average of the numbers,
- Calculate the sum and divide it by the length of the array
Use the reduce method when the array contains only numbers, and you do not want to make any explicit checks on each array item.
Code
var myArray = [ 0, 1, 2, 3, 4, 5, ];
const sum = myArray.reduce((a, b) => a + b, 0);
const average = (sum / myArray.length) || 0;
console.log(`The sum is: ${sum}. The average is: ${average}.`); //"The sum is: 15. The average is: 2.5."
Using For Loop
The for
loop is used to perform an iteration for n number of times.
To calculate the sum of numbers,
- Iterate with the
for
loop for the array length times - During each iteration, add the element to the sum
To calculate the average of the numbers,
- Divide the sum by the length of the array.
Use this method when your array contains undefined or falsy values. Before adding it to the sum, you can check if the current element is a number. Reduce()
method will not work with the undefined values.
Code
var myArray = [0, 1, 2, 3, 4, 5, ];
var sum = 0;
for (var i = 0; i < myArray.length; i++) {
sum += myArray[i];
}
var average = sum / myArray.length;
console.log(`The sum is: ${sum}. The average is: ${average}.`); //"The sum is: 15. The average is: 2.5."
Using Lodash
The lodash library provides many useful methods to perform various operations with a modular approach and better performance practices.
It provides two methods to calculate sum
and mean
.
- The sum() method to sum the array of elements
- The mean() method to calculate the average of the elements in the array.
You can include the lodash library using the following script.
<script src="lodash.js"></script>
Once you include the script, you can include the lodash methods using the _.
prefix.
Code
The following code demonstrates how to use the sum()
and the mean()
methods to calculate the sum and average of numbers in an array.
var myArray = [0, 1, 2, 3, 4, 5, ];
var sum = _.sum(myArray);
var average = _.mean(myArray);
console.log(`The sum is: ${sum}. The average is: ${average}.`); //"The sum is: 15. The average is: 2.5."