Calculating mean, median, mode and range isn't a very common task, but developers definitely need to know what they are and how to calculate them based on a set of numbers.
Before we proceed with the implementation, let's learn what each of these terms means.
Mean is the average of all the numbers in an array.
It can be calculated by adding all numbers and dividing by the array size.
Let's calculate the mean for the following array: [2, 4, 5, 7, 1, 8, 1]:
The mean value is 4.
const mean = arr => {
let total = 0;
for (let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total / arr.length;
};
Median is the middle number in the sorted array of numbers.
To calculate this value, we should first sort an array and check the size - whether it is odd or even.
If the size is odd, we can just take the middle number and return it.
Let's calculate the median for the following array: [2, 4, 5, 7, 1, 8, 1]:
The median value is 4.
If the size is even, we have two middle numbers, so we should calculate their average.
Let's calculate the median for the following array: [5, 6, 1, 2, 10, 8, 3, 4]:
The median value is 4.5.
const median = arr => {
const { length } = arr;
arr.sort((a, b) => a - b);
if (length % 2 === 0) {
return (arr[length / 2 - 1] + arr[length / 2]) / 2;
}
return arr[(length - 1) / 2];
};
Mode is the number that occurs most often.
If more than one number occurs equally often, the first number is returned.
If one number occurs most often, we just return it.
Mode for the following array: [2, 4, 6, 2, 2] is 2.
If a few numbers occur the same number of times, the first number found is returned.
Mode for the following array: [2, 4, 6, 2, 2, 4, 4, 6, 6] is also 2.
The algorithm is the following:
Check if the highest stored mode (count) is smaller than the processed number:
const mode = arr => {
const mode = {};
let max = 0, count = 0;
for(let i = 0; i < arr.length; i++) {
const item = arr[i];
if(mode[item]) {
mode[item]++;
} else {
mode[item] = 1;
}
if(count < mode[item]) {
max = item;
count = mode[item];
}
}
return max;
};
Range is the difference between the largest and smallest number in an array.
Let's calculate the range for the following array: [2, 4, 5, 7, 1, 8, 1]:
The range value is [1, 8].
const range = arr => {
arr.sort((a, b) => a - b);
return [arr[0], arr[arr.length - 1]];
};
In this article, we learned how to calculate the mean, median, mode and range of an array in JavaScript.
The implementation is simple as long as you know the meaning of each term.
If not, make sure you understand them and implement them at least once without any hints.