Home
plant-holly

Stats 101

For the statistically inclined, javascript implementations of mean, median and mode. We are adding methods to the Array class, allowing the behaviour to be shared amongst all array objects. (Note: I am making use of functions defined in earlier articles)

/*
    Returns a list of lists.  The internal lists are composed of a
    value and a count.  This list of lists is used to determine how
    many times a value is present in an array.
*/
Array.prototype.elementCountList = function() {
    var set = new Object();
    for(var i = 0; i < this.length; i++) {
  if (set[this[i]]) {
      set[this[i]] += 1;
  } else {
      set[this[i]] = 1;
  }
    }
    var buffer = [];
    for(var key in set) {
        buffer.push([key, set[key]]);
    }
    return buffer;
}

Array.prototype.sum = function() {
    return this.reduce(function(a, b) { return a + b; });
}

Array.prototype.mean = function() {
    var count = this.count();
    if (count) {
        return (this.sum() / count);
    } else {
        return Number.NaN;
    }
}
Array.prototype.average = Array.prototype.mean;

Array.prototype.mode = function() {
    var ecl = this.elementCountList().sort(function(a, b) { return b[1] - a[1] });
    if (ecl.length) {
        var max = ecl[0][1];
        var buffer = [];
        for(var i = 0; i < ecl.length; i++) {
      if (ecl[i][1] == max) {
    buffer.push(ecl[i][0]);
      }
  }
        return buffer;
    } else {
        return Number.NaN;
    }
}

Array.prototype.median = function() {
    var copy = this.deepCopy();
    copy.sort();
    if (copy.length % 2 == 1) {
        return copy[Math.round(copy.length / 2) - 1];
    } else {
        return (copy[Math.round(copy.length / 2) - 1] +
                copy[Math.round(copy.length / 2)]) / 2;
    }
}