How To Calculate Standard Deviation in JavaScript


By onjsdev

The standard deviation is a commonly used statistical measure that provides an insight into the variability or dispersion of a dataset. In this article we will show you how to calculate standard deviation with javascript for a given array consisting of numbers.

Let's get started.

Calculate Standard Deviation With Javascript

Before we write a code, we need to examine its formula. You can see the formula below for calculating the standard deviation of a dataset.

Formula: SD = √(Σ(x - μ)^2 / n)

Where:

  • x is a data in array,
  • μ is the mean,
  • n is the length of the array,
  • Σ is the sum of

When we want to calculate the standard deviation for a sample that is taken for entire data(population), the formula will undergo a minor modification, as follows: Formula: SD = √(Σ(x - μ)^2 / (n-1))

As you can see above, we need to utilize an array containing numbers, and the following JavaScript array methods will be applied to compute various portions of the formula.

  • Math.sqrt => Square Root
  • Math.pow => Square
  • map => (x - μ)^2
  • reduce => calculating mean and Σ((x - μ)^2)

And here is an example of javascript code snippet calculating the standard deviation of an array.

// A Dataset
const numbers = [2, 6, 7];

// Calculate mean
const mean = numbers.reduce((acc, curr) => acc + curr) / numbers.length;

// For the sample numbers.length - 1
const length = numbers.length;

const sd = Math.sqrt(
  numbers
    .map((number) => Math.pow(number - mean, 2))
    .reduce((acc, curr) => acc + curr) / length
);

console.log(sd);
// 2.1602

Conclusion

To sum up, standart deviation is usefeul measure that indicate variability in a data set so we have shown how to calculate it with javascript using array reduce and map methods and math library.

Thank you for reading.