Onjsdev

Share


How To Calculate Standard Deviation in JavaScript


By onjsdev

Dec 23rd, 2023

Standard deviation is a measure of how spread out a set of data is from its mean. In this article we will show you how to calculate standard deviation of a array of numbers with Javascript.

Let's get started.

How To Calculate Standard Deviation With Javascript

Before implementing the code, let's examine the formula of standard deviation of an array of numbers.

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

To implement the formula, we will use an array of numbers and the following JavaScript array methods to calculate the different portions of the formula:

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

And here is implementation 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 dataset. In this article, we have shown how to calculate the standard deviation of an array of numbers in javascript.

Thank you for reading.