Onjsdev

Share


How to Calculate Variance With JavaScript


By onjsdev

Dec 11th, 2023

Variance is the statistical measurement of how spread out data is around its average value. It helps to show how different each number is from the average (or mean) of the dataset.

In this article we will show you how to calculate variance with javascript for a given array. Let's get started.

How To Calculate Variance In Javascript

You can see the formula below for calculating the variance of a dataset.

Formula: V = (Σ(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 utilize the following JavaScript array methods to calculate the variance

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

And here is the code calculating the variance of an array in javascript.

// A Dataset
const numbers = [1, 2, 3, 4, 5];

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

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

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

console.log(v); // 2

Conclusion

In conclusion, variance is useful measure that indicate variability in a dataset and it can be easily calculated with javascript using an array and some methods such as map and reduce.

Thank you for reading.