const average = arr => arr.reduce((a,b) => a + b, 0) / arr.length; average([99, 45, 26, 7, 11, 122, 22]); //47.42857142857143
Restrict the number of decimal points, using toFixed().
average([99, 45, 26, 7, 11, 122, 22]).toFixed(2); //47.43
We can implement the average() to accept a list of arguments instead of an array like:
const average = (...args) => args.reduce((a, b) => a + b) / args.length; average(99, 45, 26, 7, 11, 122, 22).toFixed(2); //47.43
That’s it. Find out how to calculate median of an array.
Leave a Reply