Standard deviation javascript

tc03 picture tc03 · Sep 8, 2011 · Viewed 32k times · Source

I am trying to get the standard deviation of a user input string. I have as follows, but it returns the wrong value for SD. The calculation should go as follows: Sum values/number values = mean Square (sum each value-mean) Sum squares/number values.

Assistance appreciated (and explanation if possible):

Answer

Foxcode picture Foxcode · Dec 2, 2018

Shorthand method for getting standard deviation from an array if you don't like lots of code:

function getStandardDeviation (array) {
  const n = array.length
  const mean = array.reduce((a, b) => a + b) / n
  return Math.sqrt(array.map(x => Math.pow(x - mean, 2)).reduce((a, b) => a + b) / n)
}