Find the average of an array with Javascript
Published
Sadly there are no math function to easily calculate the average in Javascript, so we need to do it ourselves.
How to find the average of two or more numbers
Let’s get into some simple maths to get started. The average is the sum of a set of values divided by their count.
const first = 10;
const second = 20;
const third = 30;
// Calculating the average of two numbers
const averageTwo = (first + second) / 2; // (10 + 20) / 2
console.log(averageTwo); // prints 15
// Calculating the average of three numbers
const averageThree = (first + second + third) / 3; // (10 + 20 + 30) /3
console.log(averageThree); // prints 20
Now that we know how it works, let’s find out how to generalize the calculation to an array of numbers. I go over the code responsible for summing in my article about finding the sum of an array in Javascript
How to calculate the average using a loop
This is a pretty straightforward solution using a for loop. We just create an accumulator variable that will hold the total obtained from the addition of all values in the array.
const myArray = [1, 3, 6, 8];
const length = myArray.length;
// We'll define an accumulator variable
let total = 0;
// We then loop over the array and add them to the accumulator
for (let index = 0; index < length; index++) {
total += myArray[index];
}
const average = total / length;
console.log(average); // prints 4.5
How to calculate the average using reduce
Reduce is a method accessible on all Arrays. They let you defice a reducer function that will be applied on each element of the array. In our case, we’ll be using it to get the sum of all elements in the array.
const myArray = [1, 3, 6, 8];
// Reduce lets us sum the values contained in the array. We give it an optional starting value of 0.
const total = myArray.reduce((previous, current) => previous + current, 0);
const average = total / myArray.length;
console.log(average); // prints 4.5