Computer >> Computer tutorials >  >> Programming >> Javascript

Average with the Reduce Method in JavaScript


We are required to write a JavaScript function that takes in array of Numbers. The function should calculate the average of all the numbers in the array.

The only condition for us is that we have to do this using Array.prototype.reduce() method.

Example

const arr = [129, 139, 155, 176];
const calculateAverage = (arr = []) => {
   const reducer = (acc, value, index, array) => {
      let val = acc + value;
      if (index === array.length - 1) {
         return val / array.length;
      };
      return val;
   };
   const res = arr.reduce(reducer, 0);
   return res;
};
console.log(calculateAverage(arr));

Output

And the output in the console will be −

149.75