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

To find the standard deviation of all elements in an array in JavaScript, you can use the following function:

index.tsx
function standardDeviation(arr) {
  const n = arr.length;
  const mean = arr.reduce((acc, val) => acc + val, 0) / n;
  const variance = arr.reduce((acc, val) => acc + (val - mean) ** 2, 0) / n;
  const stdDev = Math.sqrt(variance);
  return stdDev;
}
251 chars
8 lines

You can call this function by passing in an array argument, like so:

index.tsx
const myArray = [2, 4, 6];
const result = standardDeviation(myArray);
console.log(result); // output: 1.63299...
113 chars
4 lines

This code calculates the sample standard deviation of the elements in the array using the formula sqrt(sum of (each element minus the mean) squared divided by number of elements).

gistlibby LogSnag