Calculating Mean, Median, and Mode in JavaScript

on in JavaScript, JavaScript Arrays & Objects
Last modified on

When dealing with statistics, three key measures often come into play — mean, median, and mode. These statistical metrics help us understand data distributions, offering insights into the central tendencies of a data set. In this tutorial, we’ll walk through how to calculate each of these using JavaScript. We’ll break down each function with code examples, explanations, and extensive comments to ensure everything is crystal clear.

Mean is the average of the dataset, calculated by summing all values and dividing by the number of elements.
Median is the middle value in the dataset when sorted. For even-sized datasets, it is the average of the two middle values.
Mode represents the number(s) that appear most frequently. If all values have the same frequency, no mode exists.

Let’s dive in!

Overview of Central Tendency

  1. Mean: The average of all the numbers in a dataset.
  2. Median: The middle value when the numbers are sorted in order.
  3. Mode: The number(s) that appear most frequently in the dataset.

Example Dataset:

const data = [25, 17, 40, 63, 25, 54, 70];

Step-by-step Breakdown:

1. Calculating the Mean

The mean is simply the sum of all numbers divided by the count of numbers. In JavaScript, we can calculate it using the reduce method to sum up the array elements and then dividing by the array length.

Code Explanation:

/**
 * Calculates the mean (average) of a given array of numbers.
 *
 * @param {number[]} arr - The array of numbers.
 * @return {number} - The mean value.
 */
function mean(arr) {
    // Use reduce to sum all the values in the array.
    let sum = arr.reduce((a, b) => a + b, 0);

    // Divide the total sum by the length of the array to get the mean.
    return sum / arr.length;
}
  • arr.reduce((a, b) => a + b, 0): The reduce function iterates over the array, summing up its elements. The 0 represents the initial value of the accumulator.
  • sum / arr.length: We then divide the total sum by the number of elements in the array to get the average (mean).

2. Calculating the Median

The median represents the middle value of a sorted dataset. If the array length is odd, the median is the middle number. If even, it’s the average of the two middle numbers.

Code Explanation:

/**
 * Calculates the median of a given array of numbers.
 * If the array length is even, it returns the average of the two middle numbers.
 *
 * @param {number[]} arr - The array of numbers.
 * @return {number} - The median value.
 */
function median(arr) {
    // Sort the array in ascending order.
    const arrSorted = arr.sort((a, b) => a - b);

    // If the array length is even, return the average of the two middle numbers.
    // Otherwise, return the middle element.
    return arrSorted.length % 2 === 0
        ? (arrSorted[arrSorted.length / 2 - 1] + arrSorted[arrSorted.length / 2]) / 2
        : arrSorted[Math.floor(arrSorted.length / 2)];
}
  • arr.sort((a, b) => a - b): Sorts the array in ascending order so we can easily pick the middle element(s).
  • The length % 2 === 0 check determines if the array length is even or odd.
    • If even, it averages the two middle elements.
    • If odd, it returns the exact middle element by using Math.floor(arr.length / 2) to calculate the index.

3. Calculating the Mode

The mode is the number (or numbers) that appear most frequently in a dataset. There can be more than one mode, or no mode at all if all numbers appear with equal frequency.

Code Explanation:

/**
 * Calculates the mode(s) of a given array of numbers.
 * If there is more than one mode, it returns an array of modes.
 * If all numbers have the same frequency, it returns an empty array.
 *
 * @param {number[]} arr - The array of numbers.
 * @return {number[]} - An array of modes or an empty array if no mode exists.
 */
function mode(arr) {
    // Create a frequency table to count occurrences of each number.
    const frequencyTable = {};
  
    // Iterate over the array, populating the frequency table.
    arr.forEach(elem => frequencyTable[elem] = frequencyTable[elem] + 1 || 1);

    // Initialize variables to track the modes and the highest frequency.
    let modes = [];
    let maxFrequency = 0;

    // Loop through the frequency table to find the number(s) with the highest frequency.
    for (const key in frequencyTable) {
        if (frequencyTable[key] > maxFrequency) {
            // If the current frequency is higher than maxFrequency, reset modes array.
            modes = [Number(key)];
            maxFrequency = frequencyTable[key];
        } else if (frequencyTable[key] === maxFrequency) {
            // If the frequency matches the max frequency, add this number to modes.
            modes.push(Number(key));
        }
    }

    // If all numbers occur with the same frequency, there is no mode.
    if (modes.length === Object.keys(frequencyTable).length) modes = [];

    return modes;
}

Frequency Table Creation:
arr.forEach(elem => frequencyTable[elem] = frequencyTable[elem] + 1 || 1)
This iterates over the array and creates a key-value pair in frequencyTable, where the key is the number and the value is its frequency.

Finding the Mode:
We then loop through the frequency table to find the highest frequency. If a number’s frequency exceeds the current maxFrequency, we update modes. If multiple numbers have the same frequency, we collect them in the modes array.

Edge Case:
If all numbers appear the same number of times, modes.length will equal the number of unique elements in the array, so we return an empty array to indicate no mode.

Example Usage:

Now that we have defined the functions for mean, median, and mode, let’s apply them to our dataset and see the results.

// Example data
const data = [25, 17, 40, 63, 25, 54, 70];

console.log(`Data: ${data}`);
console.log(`Mean: ${mean(data)}`);
console.log(`Median: ${median(data)}`);
console.log(`Mode: ${mode(data)}`);

Output:

Data: 25,17,40,63,25,54,70
Mean: 42
Median: 40
Mode: [25]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *