Mean of an Array Rounded Down to Nearest Integer in JavaScript



Problem

We are required to write a JavaScript function that takes in an array of numbers. Our function is supposed to return the average of the given array rounded down to its nearest integer.

Example

Following is the code −

 Live Demo

const arr = [45, 23, 67, 68, 12, 56, 99];
const roundedMean = (arr = []) => {
   const { sum, count } = arr.reduce((acc, val) => {
      let { sum, count } = acc;
      count++;
      sum += val;
      return { sum, count };
   }, {
      sum: 0, count: 0
   });
   const mean = sum / (count || 1);
   return Math.round(mean);
};
console.log(roundedMean(arr));

Output

Following is the console output −

53
Updated on: 2021-04-20T06:22:24+05:30

331 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements