Find the mean of a set of numbers

Darren Jones
April 27, 2021

This function returns the arithmetic mean of a list of numbers. The numbers can be entered as an array or individual parameters

copy code
// Returns the mean of a list of numbers
// @numbers can be a list of parameters or an array

const mean = (...numbers) => numbers.flat().reduce( (sum,number) => sum + number)/numbers.flat().length

// 40
// 2

This function accepts either a list of numbers as separate parameters or an array of numbers. This is done by using the rest operator (...) as the parameter. This will produce an array of all the numbers provided as arguments. If an array is provided as a single argument then it will result in numbers being a nested array, so we need to use the flat() method to flatten this to a single array. We then use the reduce method to cumulatively add all the values together to get the sum of all the numbers. We then divide by the length of the flattened array, as this tells us how many numbers were in the calculation.

Know a better answer? Join our our community and let us know.