• # JavaScript Statistics and Math Library Recently I started my own Google Code project to share some of the reusable code I have developed. There are lots of good general purpose JavaScript libraries such as jQuery or Closure but sometimes there are things that are out of the scope for these types of libraries. One of those things is basic math and statistics operations.

Update: Version 2.0 is out now. Check it out here.

This deficiency became apparent to me while coding something for work where I wanted to use JavaScript to calculate some basic math and statistics: mean, variance, standard deviation, etc. There weren’t any good libraries or code snippets I could find to do these functions easily.

I ended up throwing something together that got the job done but later decided that I could make it a lot more simple and reusable. Turns out that JavaScript’s prototyping capability is perfect for these types of operations. It turns Math.max.apply(Math, myArray) into myArray.max().

These are the methods I have implemented so far:

• Array.prototype.sum(): returns sum of all array values
• Array.prototype.min(): returns the lowest numeric value of an array
• Array.prototype.max(): returns the highest numeric value of an array
• Array.prototype.mean(): returns the arithmetic mean of an array
• Array.prototype.median(): returns the median of an array
• Array.prototype.sortNumber(boolean decending): returns array sorted ascending, or descending if sortNumber(true)
• Array.prototype.variance(): returns the variance of an array
• Array.prototype.stdDev(): returns standard deviation of an array
• normsinv(p): returns lower tail quantile for standard normal distribution function

These are just some basic Excel-type of functions. I am open to adding more functionality to the library, so if you would like to contribute some code or just have a suggestion for a useful function then please leave comment.

Download the script and examples here. You can also link against the minified version here if you would always like to use the latest version. 