Finding the average and the median of an array using JavaScript can be a fairly painless process. If you do it right, it should only take a few lines of code to calculate the correct averages and medians for any given array.
The average, which is the sum of all the values divided by the number of values, you’ll need to find the length of the array, sum up all of the values using the .reduce() method (the .reduce() method will reduce the values of an array to a single value by adding them all together), and divide the sum by the array’s length.
var values = [4, 9, 3, 17, 12] var sum = values.reduce((previous, current) => current += previous); var avg = sum / values.length; // avg = 9
To find the median or the value or values that lie in the middle of an array when the array is in numerical order, you need to .sort() the array to make sure that the values are properly arranged, then get the mean of the middle values, like this:
var values = [7, 6, 29, 3, 88, 11]; values.sort((a, b) => a - b); var lowMiddle = Math.floor((values.length - 1) / 2); var highMiddle = Math.ceil((values.length - 1) / 2); var median = (values[lowMiddle] + values[highMiddle]) / 2; // median = 20