Results 1 to 2 of 2

Thread: median js

  1. #1
    Join Date
    Mar 2011
    Location
    N 11 19' 0.0012 E 142 15' 0
    Posts
    1,521
    Thanks
    41
    Thanked 89 Times in 88 Posts
    Blog Entries
    3

    Default median js

    I'm doing all the basic average functions (Maths)

    Code:
    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???
    Last edited by keyboard; 05-03-2012 at 01:44 AM. Reason: Edited script

  2. #2
    Join Date
    Mar 2011
    Location
    N 11 19' 0.0012 E 142 15' 0
    Posts
    1,521
    Thanks
    41
    Thanked 89 Times in 88 Posts
    Blog Entries
    3

    Default

    Hmmm, another question to add on to that -

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

    Code:
    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???
    Last edited by keyboard; 05-03-2012 at 01:55 AM. Reason: BBcode, what bbcode?

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •