Posted on

Basic statistics in javascript 1

In this post I would like to talk a little bit about making statistics with javascript. I am not an expert neither in javascript nor math, but sometimes I need to recalculate, standardize or analyse some values. I have created some function, all of them will have input of array with values. Output will be a number or an array with numbers as a result of chosen statistic operation.

 

Sum

The first operation I would like to talk about is sum, because it is very simple. First option is to just iterate through all the values in array:

The second option is to use “Array.prototype.reduce” method:

 

Arithmetic mean

Most of people would just say “average”. But in statistics, there are lot of so called “measures of central tendency” that define center of the distribution. Arithmetic mean is very easy to calculate, it is just a sum divided by number of elements:

 

Median

Another “measure of central tendency” is median. It is the middle value that separates the higher half from the lower half of the data set. If the number of values is odd, we just pick the middle one after sorting the array. The problem is, when we have even number of values. In this case we just sum two “middle” values and divide them by two. Even number will return “0” after %2.

 

Mode 

Mode is the next central tendency value and shows the number that is in the set as most frequent one. If there are more values as most frequent and you need just one, this is one option:

all the values are saved in js object “modeMap” and variable “maxEl” is the most frequent value.

There is a possibility, more values are most frequent and in this case you would like to return an array of this values:

In our code we added lines for getting all the values and keys from object. Then we found maximal frequency and iterated all the values to found all the keys.

 

There are more “measure of central tendency” but really dont know why would one use them.