ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ตัวเลข ฟังก์ชันควรคืนค่าค่าเฉลี่ยของอาร์เรย์ที่ปัดลงเป็นจำนวนเต็มที่ใกล้ที่สุด (floor)
ตัวอย่าง
โค้ดตัวอย่างด้านล่าง:
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));
ผลลัพธ์
53
คำอธิบายเพิ่มเติม
โค้ดใช้ reduce สะสม sum และ count แล้วคำนวณค่าเฉลี่ย แต่ใช้ Math.round() ไม่ใช่ Math.floor() ตามโจทย์ที่บอก "rounded down" (ปัดลง) ควรใช้ Math.floor() เพื่อปัดลงเสมอ