Mean of an array rounded down to nearest integer in JavaScript

JavascriptWeb DevelopmentFront End Technology

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
raja
Published on 20-Apr-2021 06:21:54
Advertisements