PDA

View Full Version : median js

keyboard
05-02-2012, 07:12 AM
I'm doing all the basic average functions (Maths)

function median(elem,returnType) {
if(typeof returnType == "undefined") {
var returnType = "1";
}
elem.sort(sortMethod);
var numType;
var half1 = elem.length / 2;
var half2;
var halfminused;
var halfdivided;
var plus1;
var median;
if(elem.length % 2) {
plus1 = Math.floor(half1); //As i[1] is actually the second value in an array not the first, we've got to floor() it instead of ceil();
median = elem[plus1];
} else {
half2 = half1 + 1;
halfminused = half2 - half1;
halfdivided = halfminused / 2;
median = half1 + halfdivided;
}
if(returnType == "1") {
return {median : median};
} else {
if(returnType == "2") {
return median;
}
}
return median;
}

Is there a simpler way to do this???

keyboard
05-03-2012, 01:55 AM
Hmmm, another question to add on to that -

How would you find the most common value in an array (not jQuery):

var array1=new Array();
array1[0]="1";
array1[1]="4";
array1[2]="4";
array1[3]="4";
array1[4]="5";
array1[5]="5";
array1[6]="7";

Run it through a function and it should output 4 (maths - averages - mode).

Any help???