Are mean mode of a dataset equal in JavaScript

We are required to write a JavaScript function that takes in an array of numbers and checks if the mean and mode are equal. The function should calculate both statistical measures and return true if they match, false otherwise.

For example ?

If the input array is ?

const arr = [5, 3, 3, 3, 1];

Then the output for this array should be true because both the mean and mode of this array are 3.

Understanding Mean and Mode

The mean is the average of all numbers in the dataset. The mode is the number that appears most frequently in the dataset.

Complete Solution

const arr = [5, 3, 3, 3, 1];

// Function to calculate mean (average)
const mean = arr => (arr.reduce((a, b) => a + b)) / (arr.length);

// Function to calculate mode (most frequent value)
const mode = arr => {
    let obj = {}, max = 1, mode;
    
    // Count frequency of each number
    for (let i of arr) {
        obj[i] = obj[i] || 0;
        obj[i]++;
    }
    
    // Find the number with highest frequency
    for (let i in obj) {
        if (obj.hasOwnProperty(i)) {
            if (obj[i] > max) {
                max = obj[i];
                mode = i;
            }
        }
    }
    return +mode; // Convert string back to number
};

// Function to check if mean equals mode
const meanMode = arr => mean(arr) === mode(arr);

console.log("Array:", arr);
console.log("Mean:", mean(arr));
console.log("Mode:", mode(arr));
console.log("Are mean and mode equal?", meanMode(arr));
Array: [ 5, 3, 3, 3, 1 ]
Mean: 3
Mode: 3
Are mean and mode equal? true

Testing with Different Arrays

// Test case 1: Mean and mode are equal
const arr1 = [2, 2, 2];
console.log("Array 1:", arr1);
console.log("Mean and mode equal?", meanMode(arr1));

// Test case 2: Mean and mode are different
const arr2 = [1, 2, 3, 4, 4];
console.log("Array 2:", arr2);
console.log("Mean:", mean(arr2));
console.log("Mode:", mode(arr2));
console.log("Mean and mode equal?", meanMode(arr2));
Array 1: [ 2, 2, 2 ]
Mean and mode equal? true
Array 2: [ 1, 2, 3, 4, 4 ]
Mean: 2.8
Mode: 4
Mean and mode equal? false

How the Solution Works

The solution consists of three functions:

  • mean() - Sums all elements and divides by array length
  • mode() - Counts frequency of each number and returns the most frequent one
  • meanMode() - Compares the results of mean and mode functions

The mode function uses an object to track frequency counts, then finds the key with the highest count value.

Conclusion

This approach efficiently determines if a dataset's mean and mode are equal by calculating both statistical measures and comparing them. The solution handles various array types and provides accurate results for statistical analysis.

Updated on: 2026-03-15T23:19:00+05:30

238 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements