Skip to content

Instantly share code, notes, and snippets.

@stekhn
Last active July 8, 2016 17:58
Show Gist options
  • Save stekhn/2e998249b393a6418ec0bbbc3fc85f54 to your computer and use it in GitHub Desktop.
Save stekhn/2e998249b393a6418ec0bbbc3fc85f54 to your computer and use it in GitHub Desktop.
Standard deviation in JavaScript
function stdDev(arr) {
var avg = mean(arr);
var squareDiffs = arr.map(function (value) {
var diff = value - avg;
var sqrDiff = diff * diff;
return sqrDiff;
});
return Math.sqrt(mean(squareDiffs));
}
function mean(arr) {
return arr.reduce(function (previous, current) {
return previous + current;
}, 0) / arr.length;
}
stdDev([251, 360, 210, 900, 425, 12]);
// => 274.25940680717264
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment