find the variance of all elements in an array in javascript

To find the variance of all elements in an array in JavaScript, you can use the following algorithm:

  1. Find the mean of the array elements
  2. Calculate the difference between each array element and the mean
  3. Square the differences obtained in step 2
  4. Find the sum of the squared differences
  5. Divide the sum obtained in step 4 by the number of elements in the array minus 1

Here's the JavaScript code to implement the above algorithm:

index.tsx
function arrayVariance(arr) {
  const mean = arr.reduce((a, b) => a + b) / arr.length;
  return arr.reduce((acc, val) => acc + Math.pow(val - mean, 2), 0) / (arr.length - 1);
}

const arr1 = [1, 2, 3, 4, 5];
console.log(arrayVariance(arr1)); // Output: 2.5

const arr2 = [11, 12, 13, 14, 15];
console.log(arrayVariance(arr2)); // Output: 2.5
342 chars
11 lines

In the above code, we use the reduce method to calculate the mean and the sum of squared differences of the array elements. Finally, we divide the sum of squared differences by the number of elements minus 1 to get the variance of the array elements.

gistlibby LogSnag