Introduction
In this lab, we will explore the concept of standard deviation in statistics and its implementation in JavaScript. We will learn how to calculate the standard deviation of an array of numbers using the Array.prototype.reduce() method and understand the difference between sample and population standard deviation. By the end of this lab, you will have a better understanding of statistical analysis and how to apply it in JavaScript programming.
Standard Deviation
To calculate the standard deviation of an array of numbers in JavaScript, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the function
standardDeviation(arr, usePopulation = false)provided below. - Pass an array of numbers as the first argument to the function.
- Omit the second argument,
usePopulation, to get the sample standard deviation. Set it totrueto get the population standard deviation.
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((val - mean) ** 2), [])
.reduce((acc, val) => acc + val, 0) /
(arr.length - (usePopulation ? 0 : 1))
);
};
Example usage:
standardDeviation([10, 2, 38, 23, 38, 23, 21]); // 13.284434142114991 (sample)
standardDeviation([10, 2, 38, 23, 38, 23, 21], true); // 12.29899614287479 (population)
Summary
Congratulations! You have completed the Standard Deviation lab. You can practice more labs in LabEx to improve your skills.