Array average and median - Node.js Algorithm

Node.js examples for Algorithm:Statistics

Description

Array average and median

Demo Code


/**/*  ww  w  .j a va2 s  . c  om*/
 *
 * @return {Number} median value
 *
 */
Array.prototype.median = function() {
    var type = Object.prototype.toString.call(this).split(/\W/)[2];
    if (type === 'Array') {
        var median = 0;
        this.sort();
        if (this.length % 2 === 0) {
            median = (this[this.length / 2 - 1] + this[this.length / 2]) / 2;
        }
        else {
            median = this[(this.length - 1) / 2];
        }
        return median;
    }
};

/**
 * http://stackoverflow.com/questions/10359907/array-sum-and-average
 *
 * @return {Number} average  value
 *
 */
Array.prototype.average = function(){
    var type = Object.prototype.toString.call(this).split(/\W/)[2];
    if (type === 'Array') {
        var sum = 0;
        for (var i=0; i<this.length, isFinite(this[i]); i++) {
            sum += parseFloat(this[i]);
        }
        return sum/this.length-1;
    }
};

Related Tutorials