diff --git a/README.md b/README.md index befac0394..d0393e21a 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,7 @@ * [Similarity between arrays](#similarity-between-arrays) * [Sleep](#sleep) * [Sort characters in string (alphabetical)](#sort-characters-in-string-alphabetical) +* [Standard deviation](#standard-deviation) * [Sum of array of numbers](#sum-of-array-of-numbers) * [Swap values of two variables](#swap-values-of-two-variables) * [Tail of list](#tail-of-list) @@ -696,6 +697,24 @@ const sortCharactersInString = str => // sortCharactersInString('cabbage') -> 'aabbceg' ``` +### Standard deviation + +Use `Array.reduce()` to calculate the mean, variance and the sum of the variance of the values, the variance of the values, then +determine the standard deviation. +You can omit the second argument to get the sample standard deviation or set it to `true` to get the population standard deviation. + +```js +const standardDeviation = (arr, usePopulation = false) => { + const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length; + return Math.sqrt( + arr.reduce((acc, val) => acc.concat(Math.pow(val - mean, 2)), []) + .reduce((acc, val) => acc + val, 0) / (arr.length - (usePopulation ? 0 : 1)) + ); + } +// standardDeviation([10,2,38,23,38,23,21]) -> 13.284434142114991 (sample) +// standardDeviation([10,2,38,23,38,23,21], true) -> 12.29899614287479 (population) +``` + ### Sum of array of numbers Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`.