find the standard deviation of all elements in an array in typescript

Here's a code snippet that calculates the standard deviation of all elements in an array in TypeScript:

index.ts
function calcStandardDeviation(arr: number[]): number {
  const mean = arr.reduce((acc, val) => acc + val) / arr.length;
  const variance = arr.reduce((acc, val) => acc + Math.pow(val - mean, 2), 0) / arr.length;
  return Math.sqrt(variance);
}

const arr = [1, 2, 3, 4, 5];
const stdDev = calcStandardDeviation(arr);
console.log(stdDev); // Output: 1.4142135623730951
369 chars
10 lines

Here, the calcStandardDeviation function takes an array of numbers as its argument and returns the standard deviation of its elements. The formula used to calculate the standard deviation is:

index.ts
sqrt(sum((x - mean)^2) / n)
28 chars
2 lines

where x is an element in the array, mean is the mean of all elements in the array, and n is the number of elements in the array.

The calcStandardDeviation function first calculates the mean of all elements in the array using the reduce method. It then calculates the variance of the elements using the reduce method as well. Finally, it returns the square root of the variance, which gives the standard deviation of the elements in the array.

In the example, we have an array [1, 2, 3, 4, 5] and calling the function with this array returns 1.4142135623730951 as the standard deviation.

gistlibby LogSnag