Javascript

Array Average and Median in Javascript

If you are wondering how to find the Array Average in Javascript then you all are in the right place. This article includes all about the Javascript Array Average and how to find it. So without wasting much time, let’s get started.

Also Read: How to convert a comma-separated string into Array.

Calculate the Array Average in Javascript

For finding out the average of an array in Javascript, you need to iterate through the array. If your values are strings, they need to be converted to an integer first. And average is just the sum of values divided by the number of values. Here is an example of the same.

var sum = 0;
for( var i = 0; i < elmt.length; i++ ){
    sum += parseInt( elmt[i], 10 ); //don't forget to add the base
}

var avg = sum/elmt.length;

document.write( "The sum of all the elements is: " + sum + " The average is: " + avg );

Calculate the Array Median in Javascript

You can easily find out the Array Median in Javascript using the Math.floor and Math.ceil methods. The median is the value separating the higher half from the lower half of a data sample. But in the case of Array, you need to do the following things as shown below.

let values = [2, 56, 3, 41, 0, 4, 100, 23];
values.sort((a, b) => a - b);
let lowMiddle = Math.floor((values.length - 1) / 2);
let highMiddle = Math.ceil((values.length - 1) / 2);
let median = (values[lowMiddle] + values[highMiddle]) / 2;
// median = 13,5

So this is all about how to find Array average and median in Javascript. Don’t forget to also read our blog post on – Javascript Closure

Leave a Comment