JavaScript: Finding the Mean (Average) of an Array

Updated: March 13, 2023 By: Khue Post a comment

This succinct, practical article shows you some different ways to find the mean (the average value) of a given array in JavaScript (assuming that the array contains only numeric elements).

Introduction

Calculating the mean of an array is a common task in many real-world applications. Here are some examples of where this might be useful:

  • Review & Rating: The mean can be used to calculate average user ratings of a product, a game, a movie, or something like that
  • E-commerce: In e-commerce, calculating the average order value (AOV) is an important metric for businesses. AOV is calculated by dividing the total revenue by the total number of orders.
  • Analytics: In social media, calculating the average engagement rate is a common task. The engagement rate is calculated by dividing the total number of engagements (likes, comments, shares) by the total number of impressions (views).

Text can be boring and not quite useful. Let’s explore the solutions to get the job done and make our hands dirty by writing some code (the last solution involves assigning weights to each value in an array and calculating the mean based on those weights).

Using the reduce() method

What we will do is use the reduce() method to sum up all the elements of the array and divide by the length of the array. Example:

const mean = data => {
  if (data.length < 1) {
    return;
  }
  return data.reduce((prev, current) => prev + current) / data.length;
};

const array = [1, 2, 3, 4, 5, 5.5, 6.6, 10, 11.9, 12];
console.log(mean(array));

Output:

6.1

In my opinion, this is the most elegant way to tackle the task.

Use the forEach() method

Another approach is to use the forEach() method to iterate through the array and add each element to a variable that stores the sum, then divide by the length of the array.

Example:

const numbers = [10, 20, 30, 40];
let sum = 0;
numbers.forEach((number) => {
  sum += number;
});
let avg = sum / numbers.length;
console.log(avg);

Output:

25

Using a for loop

A classic for loop can also help us calculate the mean of an array.

Example:

const mean = (array) => {
  let sum = 0;
  for (let i = 0; i < array.length; i++) {
    sum += array[i];
  }
  return sum / array.length;
}

console.log(mean([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
console.log(mean([-1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5]))

Output:

5.5
5.7

Weighted Mean Calculation

A weighted mean is a type of average that gives different weights or importance to each value in a data set. It is calculated by multiplying each value by its corresponding weight, adding up all the products, and dividing by the sum of all the weights. A weighted mean can be useful when some values are more relevant or frequent than others. For example, if you want to calculate your grade point average (GPA), you need to use a weighted mean because different courses have different credits.

Here is the code example for the weighted mean for GPA:

// Define an array of courses with grades and credits
const courses = [
  { grade: 4.0, credits: 3 },
  { grade: 3.7, credits: 4 },
  { grade: 3.3, credits: 2 },
];

// Define a function to calculate the weighted mean
const weightedMean = (data, valueVar, weightVar) => {
  // Initialize the sum of values and weights
  let sumValue = 0;
  let sumWeight = 0;

  // Loop through each element of the data array
  for (let element of data) {
    // Multiply the value by the weight and add to the sum of values
    sumValue += element[valueVar] * element[weightVar];
    // Add the weight to the sum of weights
    sumWeight += element[weightVar];
  }

  // Return the quotient of the sum of values and weights
  return sumValue / sumWeight;
};

// Call the function with courses array and grade and credit variables
const gpa = weightedMean(courses, 'grade', 'credits');

// Log the result to console
console.log(gpa);

Output:

3.711111111111111

Afterword

You’ve explored a couple of different ways to calculate the average value of a given array in JavaScript. Among these methods, the last method is completely different from the rest because it is related to the weights of the elements.

If you find errors or anachronisms in the code examples, please let us know by leaving comments. We will review and update them as soon as possible. Have a nice day and happy JavaScripting!