Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to calculate the average of an array

Short answer

Add up all the elements with reduce() and divide by their number:

const scores = [4, 5, 3, 5, 4];
const average = scores.reduce((sum, score) => sum + score, 0) / scores.length;
 
console.log(average);

Output:

4.2

An object field

For an array of objects, add up the field you need:

const orders = [{ total: 120 }, { total: 80 }, { total: 55 }];
const average = orders.reduce((sum, order) => sum + order.total, 0) / orders.length;
 
console.log(average.toFixed(2));

Output:

85.00

Common mistake

For an empty array the result is NaN, because 0 is divided by 0. Handle this case separately:

const average = (numbers) =>
  numbers.length === 0 ? 0 : numbers.reduce((sum, n) => sum + n, 0) / numbers.length;
 
console.log([].reduce((sum, n) => sum + n, 0) / 0);
console.log(average([]));

Output:

NaN
0

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.