
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
Calculate 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