Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Mean of an array rounded down to nearest integer in JavaScript
Problem
We need to write a JavaScript function that takes an array of numbers and returns the average (mean) of the array rounded down to the nearest integer using Math.floor().
Example
Following is the code ?
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.floor(mean); // Round down to nearest integer
};
console.log(roundedMean(arr));
Output
52
Alternative Approach Using Array Methods
Here's a more concise solution using built-in array methods:
const arr = [45, 23, 67, 68, 12, 56, 99];
const roundedMeanSimple = (arr = []) => {
if (arr.length === 0) return 0;
const sum = arr.reduce((total, num) => total + num, 0);
const mean = sum / arr.length;
return Math.floor(mean);
};
console.log(roundedMeanSimple(arr));
// Test with different arrays
console.log(roundedMeanSimple([10, 20, 30])); // 20
console.log(roundedMeanSimple([15, 25, 35])); // 25
console.log(roundedMeanSimple([])); // 0
52 20 25 0
Key Points
-
Math.floor()rounds down to the nearest integer, whileMath.round()rounds to the nearest integer - The function handles empty arrays by returning 0
- Using
reduce()provides a functional programming approach to calculate the sum - For the array [45, 23, 67, 68, 12, 56, 99], the mean is 52.857..., which rounds down to 52
Conclusion
To find the mean of an array rounded down, calculate the sum using reduce(), divide by array length, and apply Math.floor(). This approach handles edge cases and provides accurate results for any numeric array.
Advertisements
