 
 Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
Advertisements
                    