MeanLoading saved progress…

Mean

Implement mean(array) — return the arithmetic mean (the average) of the numbers in array. The mean is their sum divided by how many there are: add every number up, then divide by the count. This mirrors Lodash's _.mean.

Signature

// array: number[]   — the numbers to average.
// returns: number   — the sum of the numbers divided by their count.
//   For an empty array, returns NaN (sum 0 divided by count 0).
function mean(array): number;

Examples

mean([1, 2, 3, 4]); // → 2.5
mean([10]);         // → 10
mean([2, 2, 2]);    // → 2
mean([1, 2]); // → 1.5  (the result need not be a whole number)
mean([]);     // → NaN  (no numbers to average)

Notes

  • The mean is sum ÷ count. Add every element, then divide by array.length. Nothing more.
  • An empty array gives NaN. There is no average of zero numbers; matching Lodash, mean([]) is NaN (a sum of 0 divided by a count of 0).
  • The result is not always a whole number. mean([1, 2]) is 1.5. Return the exact division result; don't round.
  • Assume the array holds numbers. You don't need to validate types or skip non-numeric entries.
  • Don't mutate the input. Read the array; return a number.
Loading editor…