Implement a function mean(array)
that returns the mean (also known as average) of the values inside array
, which is an array of numbers.
array
(Array): Array of numbers.(Number): Returns the mean of the values in array
.
mean([4, 2, 8, 6]); // => 5mean([1, 2, 3, 4]); // => 2.5mean([1, 2, 2]); // => 1.6666666666666667
The function should return NaN
if array
is empty.
mean([]); // => NaN
Implement a function mean(array)
that returns the mean (also known as average) of the values inside array
, which is an array of numbers.
array
(Array): Array of numbers.(Number): Returns the mean of the values in array
.
mean([4, 2, 8, 6]); // => 5mean([1, 2, 3, 4]); // => 2.5mean([1, 2, 2]); // => 1.6666666666666667
The function should return NaN
if array
is empty.
mean([]); // => NaN
This question is a simple one that involve two parts, summing up the numbers in the array then dividing by the number of items in the array.
This solution uses a for loop to sum up all the numbers.
/*** @param {Array} array - Array from which the elements are all numbers.* @return {Number} Returns the mean.*/export default function mean(array) {let total = 0;// Calculate the sum of all numbers in the array.for (let i = 0; i < array.length; i++) {total += array[i];}// Calculate the mean from the sum.return total / array.length;}
Array.prototype.reduce()
A shorter version is to use Array.prototype.reduce()
to perform the summation.
/*** @param {Array} array - Array from which the elements are all numbers.* @return {Number} Returns the mean.*/export default function mean(array) {return array.reduce((a, b) => a + b, 0) / array.length;}
Surprisingly enough, an empty array does not require special handling. Division by zero in JavaScript gives Infinity
if the numerator is non-zero, and `NaN when the numerator is zero, which is exactly what is required.
It is possible that the sum of the numbers in the array becomes too big that it "overflows". Strictly speaking, overflowing doesn't occur in JavaScript, values larger than Number.MAX_VALUE
are represented as Infinity
and will lose their actual value.
To handle large value cases, we can split the array into smaller equal chunks and calculate the average for each chunk. The final average can be determined by taking the average of each chunk's averages. Not all array lengths can be divided into equal chunks, so the key idea here is to divide as small as possible, then take a weighted average of the chunks that depends on the size of each chunk.
console.log()
aparecerão aqui.