Computing Statistics in JavaScript

JavaScript is a computer programming language that most often runs inside a web browser as part of a web page. It is a simple yet powerful interpreted language that includes several built-in classes and functions. One of these built-in classes is the Array class. This article shows you how to add a powerful class to your JavaScript code that finds the minimum, median, and maximum values in an array of numbers. This same function also computes the count, sum, mean, variance, and standard deviation using a numerically stable algorithm.

The Stats class

Here is the JavaScript code for the Stats class. Copy these functions into a text file named "stats.js" so that you will be able to include and use them in a web page whenever you want.

/** Returns an object that contains the count, sum,
 * minimum, median, maximum, mean, variance, and
 * standard deviation of the series of numbers stored
 * in the specified array.  This function changes the
 * specified array by sorting its contents. */
function Stats(data) {
    this.count = data.length;

    /* Sort the data so that all seemingly
     * insignificant values such as 0.000000003 will
     * be at the beginning of the array and their
     * contribution to the mean and variance of the
     * data will not be lost because of the precision
     * of the CPU. */
    data.sort(ascend);

    /* Since the data is now sorted, the minimum value
     * is at the beginning of the array, the median
     * value is in the middle of the array, and the
     * maximum value is at the end of the array. */
    this.min = data[0];
    var middle = Math.floor(data.length / 2);
    if ((data.length % 2) != 0) {
        this.median = data[middle];
    }
    else {
        this.median = (data[middle - 1] + data[middle]) / 2;
    }
    this.max = data[data.length - 1];

    /* Compute the mean and variance using a
     * numerically stable algorithm. */
    var sqsum = 0;
    this.mean = data[0];
    for (var i = 1;  i < data.length;  ++i) {
        var x = data[i];
        var delta = x - this.mean;
        var sweep = i + 1.0;
        this.mean += delta / sweep;
        sqsum += delta * delta * (i / sweep);
    }
    this.sum = this.mean * this.count;
    this.variance = sqsum / this.count;
    this.sdev = Math.sqrt(this.variance);
}
/** Returns a string that shows all the properties and
 * their values for this Stats object. */
Stats.prototype.toString = function() {
    var s = 'Stats';
    for (var attr in this) {
        if (typeof(this[attr]) != 'function') {
            s += '  ' + attr + ' ' + this[attr];
        }
    }
    return s;
}


/** Compares two objects using
 * built-in JavaScript operators. */
function ascend(a, b) {
    if (a < b)
        return -1;
    else if (a > b)
        return 1;
    return 0;
}

Using the Stats class

To use the stats class, include the "stats.js" file that you made in the head of an HTML file like this:

<script type="text/JavaScript" src="stats.js"></script>

Then you can write JavaScript to use the stats class just like you would use other built-in JavaScript classes such as Array and String as shown below.

<script type="text/JavaScript">
function testStats() {
    document.open();

    // Create an array named scores.
    var scores = [ 91, 85, 74, 91, 65, 93, 67, 90, 66,
        94, 90, 58, 94, 91, 71, 60, 90, 55, 51 ];

    // Compute statistics for all scores.
    var stats = new Stats(scores);

    // Show just the median and mean of the scores.
    document.writeln('median:  ' + stats.median + '<br />');
    document.writeln('mean:  ' + stats.mean + '<br />');

    // Show all statistics for the scores.
    document.writeln('scores:  ' + scores + '<br />');

    document.close();
}
</script>

Copyright © 2008, Maia L.L.C.  All rights reserved.

Maia L.L.C. and its employees have used their best efforts in preparing this article. These efforts include the development, research, and testing of the theories and computer programs in this article to determine their correctness. Maia L.L.C. makes no warranty of any kind, expressed or implied, with regard to these programs or the documentation contained in this article. Maia L.L.C. shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.