Get Median value from Array - Node.js Algorithm

Node.js examples for Algorithm:Statistics

Description

Get Median value from Array

Demo Code


Array.prototype.median = function(){
    var len = this.length, arr = this.slice(0).sort(function(a, b){
        return a < b ? -1 : 1;
    });/*  ww w  .  j  a  v a2s  .  c  o  m*/
    if ( len % 2 == 0 ) 
      return Math.round( ( arr[ ( len / 2 ) -1 ] + arr[ ( len / 2 ) ] ) / 2 );
    return arr[ Math.floor( len / 2 ) ];
};

Related Tutorials