โจทย์
มี array of objects ต้องการคำนวณ average ของ Level เฉพาะ objects ที่ Age ไม่ใช่ null (truthy)
ตัวอย่างโค้ด
data = [
{"Age":26,"Level":8},
{"Age":37,"Level":9},
{"Age":32,"Level":5},
{"Age":31,"Level":11},
{"Age":null,"Level":15},
{"Age":null,"Level":17},
{"Age":null,"Level":45}
];
const findAverage = arr => {
const creds = arr.reduce((acc, val) => {
const { Age, Level } = val;
let { count, sum } = acc;
if(Age){
count += 1;
sum += Level;
};
return { count, sum };
}, { count: 0, sum: 0 });
return (creds.sum)/(creds.count);
};
console.log(findAverage(data));
ผลลัพธ์
8.25
คำอธิบาย
reduce() สะสม count และ sum ของ Level เฉพาะที่ Age truthy (ไม่ใช่ null, 0, undefined, "")
ข้อมูล 4 รายการแรก Age มีค่า: Level รวม = 8+9+5+11 = 33, count = 4
Average = 33/4 = 8.25