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
Computing the mean has two steps: add every value, then divide by the number of items. The for loop version is the recommended one to internalize first because it makes both steps explicit.
for loopTrack a running total, then divide that total by array.length once the loop is done.
/*** @param {Array<number>} array* @returns {number}*/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()This version is shorter, but it is doing the same work: accumulate a total first, then divide by the array length.
export default function mean(array: Array<number>): number {return array.reduce((a, b) => a + b, 0) / array.length;}
An empty array does not need special handling here. 0 / 0 evaluates to NaN, which matches the expected behavior.
Very large totals can overflow to Infinity. That is beyond the normal scope of this interview question, but it is worth knowing that JavaScript numbers do not keep arbitrary precision for huge sums.
console.log() statements will appear here.