Mean

Easy

Prompt

Write a function mean(array) that calculates the arithmetic average of the numbers in an array. Add everything up, divide by how many there are.

If the array is empty, return NaN.

mean([1, 2, 3]); // 2
mean([1, 2, 3, 4, 5]); // 3
mean([10]); // 10
mean([]); // NaN

Playground

Hint 1

To find the mean, you need two things: the sum of all numbers and the total count. You already know the count from array.length.

Hint 2

reduce() can add up all the numbers in one pass. Then just divide by the length.

Solution

Explanation

The idea is simple: add up all the numbers, then divide by how many there are.

function mean(array) {
return (
array.reduce((sum, num) => sum + num, 0) / array.length
);
}

reduce() walks through the array and accumulates a running total. We start with 0 and add each number to it. Once we have the sum, we divide by array.length to get the average.

For mean([1, 2, 3]): the sum is 1 + 2 + 3 = 6, and there are 3 numbers, so 6 / 3 = 2.

For mean([10]): the sum is 10, there's 1 number, so 10 / 1 = 10.

For mean([]): the sum is 0 (reduce starts at 0 with nothing to add), and the length is 0. Dividing 0 / 0 gives NaN in JavaScript, which is exactly what we want for an empty array.

For loop alternative

If reduce doesn't come to mind, a plain loop works just as well:

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

Same logic, just more explicit. Add everything up, divide by the count.

Lodash provides _.mean() which does the same thing. If your project already uses Lodash, you can reach for that instead.

Resources

Lodash Mean