Calculate the average of an array of numbers in JavaScript
To calculate the average of an array of numbers in JavaScript, we sum all the values and divide it by the length of the array. We can use Array.prototype.reduce() for this purpose.
Advertisements
const average = arr => arr.reduce((a,b) => a + b, 0) / arr.length; average([99, 45, 26, 7, 11, 122, 22]); //47.42857142857143
Restrict the number of decimal points, using toFixed().
average([99, 45, 26, 7, 11, 122, 22]).toFixed(2); //47.43
Advertisements
We can implement the average() to accept a list of arguments instead of an array like:
const average = (...args) => args.reduce((a, b) => a + b) / args.length; average(99, 45, 26, 7, 11, 122, 22).toFixed(2); //47.43
That’s it. Find out how to calculate median of an array.
Here’s a github gist to calculate the sum, mean, and median of an array in JavaScript.