# calculating the average/mean

• Mar 31, 2011, 00:08
minusten
calculating the average/mean
Hi,

Im trying to calculate the mean/average of numbers in an array any suggestions with the mean() would be very much appreciated.:)

how can i get the length of an array to perform in a simple / maths problem whilst being flexiable to the length of the array?:crazy:

function sum()
{
var i=0
for (i=0, total=0;i <numbers.length; i++)
{
total += numbers[i];
}
document.getElementById("txtTotal").value = total;
}

function mean()
{

}
• Apr 10, 2011, 01:16
AllanP
Try this.
Code JavaScript:

``` var numberArray=[1,2,3,4,5], thisTotal=0,thisAverage=0; // add elements of array together for(var i=0;i<numberArray.length;i++) {thisTotal+=numberArray[i];} // calculate average thisAverage=(thisTotal/numberArray.length); // display result alert(thisAverage)```
• Apr 11, 2011, 05:00
paul_wilkins
I've whipped up some functions that calculate mean, median, mode, and range.

Code javascript:

```  function mean(numbers) { // mean of [3, 5, 4, 4, 1, 1, 2, 3] is 2.875 var total = 0, i; for (i = 0; i < numbers.length; i += 1) { total += numbers[i]; } return total / numbers.length; } function median(numbers) { // median of [3, 5, 4, 4, 1, 1, 2, 3] = 3 var median = 0, numsLen = numbers.length; numbers.sort(); if (numsLen % 2 === 0) { // is even // average of two middle numbers median = (numbers[numsLen / 2 - 1] + numbers[numsLen / 2]) / 2; } else { // is odd // middle number only median = numbers[(numsLen - 1) / 2]; } return median; } function mode(numbers) { // as result can be bimodal or multimodal, // the returned result is provided as an array // mode of [3, 5, 4, 4, 1, 1, 2, 3] = [1, 3, 4] var modes = [], count = [], i, number, maxIndex = 0; for (i = 0; i < numbers.length; i += 1) { number = numbers[i]; count[number] = (count[number] || 0) + 1; if (count[number] > maxIndex) { maxIndex = count[number]; } } for (i in count) if (count.hasOwnProperty(i)) { if (count[i] === maxIndex) { modes.push(Number(i)); } } return modes; } function range(numbers) { // range of [3, 5, 4, 4, 1, 1, 2, 3] is [1, 5] numbers.sort(); return [numbers[0], numbers[numbers.length - 1]]; }```