find the variance of all elements in an array in typescript

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

index.ts
function variance(arr: number[]): number {
  const n = arr.length;
  const avg = arr.reduce((a, b) => a + b, 0) / n;
  const diffSquaredArr = arr.map((x) => Math.pow(x - avg, 2));
  const variance = diffSquaredArr.reduce((a, b) => a + b, 0) / n;
  return variance;
}
267 chars
8 lines

This function takes an array of numbers as input and returns the variance of all elements in the array. It first calculates the average of all the elements in the array. Then, it calculates the difference between each element and the average, squares the result, and stores it in a new array. Finally, it calculates the average of the squared differences, which gives the variance of the array.

You can use this function like this:

index.ts
const arr = [1, 2, 3, 4, 5];
const variance = variance(arr);
console.log(variance); // Output: 2
97 chars
4 lines

In this example, the input array is [1, 2, 3, 4, 5], and the output is 2, which is the variance of all the elements in the array.

gistlibby LogSnag