HarryP
HarryP 3d ago β€’ 10 views

Sample JavaScript Code for Finding Average, Middle, and Most Frequent Values

Hey there! πŸ‘‹ Ever needed to find the average, middle (median), or most frequent (mode) values in a list of numbers using JavaScript? πŸ€” It sounds tricky, but it's totally doable and super useful in all sorts of situations, from analyzing survey results to building cool data visualizations. Let's break down some code examples to make it easy to understand!
πŸ’» Computer Science & Technology

1 Answers

βœ… Best Answer
User Avatar
saramorales2004 Dec 29, 2025

πŸ“š Understanding Average (Mean) in JavaScript

The average, or mean, is the sum of all values divided by the number of values. It represents the central tendency of a dataset. Here's how to calculate it using JavaScript:

  • βž• First, calculate the sum of all numbers in the array.
  • βž— Then, divide the sum by the total number of elements in the array.
html

function calculateAverage(arr) {
  if (arr.length === 0) {
    return 0; // Avoid division by zero for empty arrays
  }
  const sum = arr.reduce((acc, num) => acc + num, 0);
  return sum / arr.length;
}

const numbers = [1, 2, 3, 4, 5];
const average = calculateAverage(numbers);
console.log("Average:", average); // Output: Average: 3

πŸ“Š Understanding Median (Middle Value) in JavaScript

The median is the middle value in a sorted dataset. If there are an even number of values, the median is the average of the two middle values. Calculating the median requires sorting the array first. Here's the JavaScript code:

  • 🧺 Sort the array in ascending order.
  • πŸ“ If the array length is odd, the median is the middle element.
  • βž— If the array length is even, the median is the average of the two middle elements.
html

function calculateMedian(arr) {
  const sortedArr = [...arr].sort((a, b) => a - b); // Create a sorted copy
  const middleIndex = Math.floor(sortedArr.length / 2);

  if (sortedArr.length % 2 === 0) {
    // Even number of elements
    return (sortedArr[middleIndex - 1] + sortedArr[middleIndex]) / 2;
  } else {
    // Odd number of elements
    return sortedArr[middleIndex];
  }
}

const numbers = [5, 2, 1, 3, 4];
const median = calculateMedian(numbers);
console.log("Median:", median); // Output: Median: 3

πŸ”’ Understanding Mode (Most Frequent Value) in JavaScript

The mode is the value that appears most frequently in a dataset. A dataset can have one mode (unimodal), multiple modes (multimodal), or no mode at all (if all values appear only once). Here's the JavaScript code to find the mode:

  • πŸ—ΊοΈ Create an object (or map) to store the frequency of each number.
  • πŸ“ˆ Iterate through the array, updating the frequency count for each number.
  • πŸ” Find the number(s) with the highest frequency.
html

function calculateMode(arr) {
  const frequencyMap = {};
  let maxFrequency = 0;
  let modes = [];

  for (const num of arr) {
    frequencyMap[num] = (frequencyMap[num] || 0) + 1;

    if (frequencyMap[num] > maxFrequency) {
      maxFrequency = frequencyMap[num];
      modes = [num]; // New mode found, reset the array
    } else if (frequencyMap[num] === maxFrequency) {
      modes.push(num); // Another mode found
    }
  }

  // If all numbers appear only once, there's no mode
  if (modes.length === Object.keys(frequencyMap).length && modes.length === arr.length) {
      return []; //No mode exists
  }

  return modes;
}

const numbers = [1, 2, 2, 3, 4, 2, 5];
const mode = calculateMode(numbers);
console.log("Mode:", mode); // Output: Mode: [2]

πŸ§ͺ Practice Quiz

Test your knowledge with these practice questions! (Answers are at the end)

  1. What is the average of the numbers [10, 20, 30, 40, 50]?
  2. What is the median of the numbers [15, 5, 20, 10, 25]?
  3. What is the mode of the numbers [3, 5, 2, 5, 3, 3, 1]?
  4. What is the average of the numbers [2, 4, 6, 8]?
  5. What is the median of the numbers [1, 2, 3, 4, 5, 6]?
  6. What is the mode of the numbers [7, 8, 9, 7, 8, 7]?
  7. What is the average of an empty array?

βœ… Answers to Practice Quiz

  1. 30
  2. 15
  3. 3
  4. 5
  5. 3.5
  6. 7
  7. 0

Join the discussion

Please log in to post your answer.

Log In

Earn 2 Points for answering. If your answer is selected as the best, you'll get +20 Points! πŸš€