find the standard deviation of a list of numbers in javascript

To find the standard deviation of a list of numbers in JavaScript, you can use the following formula:

index.tsx
Math.sqrt(arr.reduce((sum, value) => {
  const mean = (arr.reduce((acc, val) => acc + val, 0) / arr.length);
  return sum + Math.pow(value - mean, 2);
}, 0) / arr.length);
172 chars
5 lines

Here's a breakdown of what's happening:

  1. Calculate the mean of the array using the reduce() method.
  2. For each value in the array, subtract the mean and square the result.
  3. Add up all of the squared differences using the reduce() method.
  4. Divide the sum by the length of the array.
  5. Take the square root of the result using the Math.sqrt() method to get the standard deviation.

You can then call this function with an array of numbers as the parameter. For example:

index.tsx
const numbers = [1, 2, 3, 4, 5];
const stdDev = Math.sqrt(numbers.reduce((sum, value) => {
  const mean = (numbers.reduce((acc, val) => acc + val, 0) / numbers.length);
  return sum + Math.pow(value - mean, 2);
}, 0) / numbers.length);
console.log(stdDev); // Output: 1.4142135623730951
287 chars
7 lines

gistlibby LogSnag