DEV Community

Cover image for Calculating the Mean of an Array in JavaScript
mrwolferinc
mrwolferinc

Posted on • Updated on • Originally published at mrwolferinc.wixsite.com

Calculating the Mean of an Array in JavaScript

Calculating the mean of a list isn't an easy task in JavaScript. The programming language does not have its built-in feature that allows you to find the mean of an array. This can be frustrating especially when you have to work with statistics. Fortunately, I have created two simple workarounds that make this process easier. They aren't too complicated and can be added to any JavaScript project without having to install external/third-party libraries. Let's take a look at them, shall we?

What is mean?

Before we look at the workarounds, you first need to know what the mean of a list is. The arithmetic mean, more commonly known as the mean or average, is the sum of the values of a data set divided by the number of values in the data set. For example, if we have a data set X={1,2,3,4,5}X=\lbrace 1,2,3,4,5\rbrace , then the mean of XX would be 3, because

1+2+3+4+55=155=3.\frac{1+2+3+4+5}{5}=\frac{15}{5}=3.

The arithmetic mean is the most common measure of central tendency, and is used in many diverse fields such as economics, anthropology, and history. It is also used in almost every academic field to some extent.

Using reduce()

The first method of calculating the mean of an array in JavaScript is by using the reduce() method:

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

const array = [1, 2, 3, 4, 5];
console.log(mean(array)); // Output: 3
Enter fullscreen mode Exit fullscreen mode

The reduce() method executes a user-supplied "reducer" callback function on each element of an array, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

In this workaround, the array (as a function parameter named data) is first checked to see if it has at least 1 element. If data does not meet this requirement, then the function returns nothing. Otherwise, the reduce() method is used on data to find the sum of its elements, and then divides the result by data's length.

This is the most straightforward workaround that exists, but it only works on arrays containing numbers. If you need to find the mean of an array containing strings as numbers, then check out the next workaround.

Using map() and reduce()

This method works on arrays containing strings as numbers. It is similar to the previous workaround, but it uses the map() method to convert the elements to numbers:

const mean = (data, asString) => {
  if (data.length < 1) {
    return;
  }
  if (asString && asString === true) {
    return String(data.map(elem => Number(elem)).reduce((prev, current) => prev + current) / data.length);
  } else {
    return data.map(elem => Number(elem)).reduce((prev, current) => prev + current) / data.length;
  }
};

const array1 = ['2', '4', '6', '8', '10'];
const array2 = ['3', '6', '9', '12', '15'];
console.log(mean(array1));       // Output: 6
console.log(mean(array2, true)); // Output: "9"
Enter fullscreen mode Exit fullscreen mode

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. In this workaround, the map() method is called on data, the reduce() method is called on the result, and the sum is divided by data's length. The function also takes an asString parameter to optionally return the mean as a string.


That's it for today's post! I hope you guys enjoyed it!

Top comments (0)