Calculating variance for an array of numbers in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of numbers sorted in increasing order.

Our function should calculate the variance for the array of numbers. Variance of a set of numbers is calculated on the basis of their mean.

$Mean (M) = ( \sum_{i=0}^{n-1} arr[i])$ / n

And variance (V) = $(\sum_{i=0}^{n-1} (arr[i] - M)^2)$ / n

Example

Following is the code −

 Live Demo

const arr = [4, 6, 7, 8, 9, 10, 10];
const findVariance = (arr = []) => {
   if(!arr.length){
      return 0;
   };
   const sum = arr.reduce((acc, val) => acc + val);
   const { length: num } = arr;
   const median = sum / num;
   let variance = 0;
   arr.forEach(num => {
      variance += ((num - median) * (num - median));
   });
   variance /= num;
   return variance;
};
console.log(findVariance(arr))

Output

4.204081632653061

Updated on: 21-Apr-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements