Cho mảng đối tượng sau:
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}
];
Yêu cầu: Viết hàm tính trung bình Level chỉ cho các đối tượng có Age là giá trị truthy (khác null, undefined, 0, "", false).
Giải pháp với reduce
const 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) { // Chỉ tính khi Age truthy
count += 1;
sum += Level;
}
return { count, sum };
}, { count: 0, sum: 0 });
return creds.sum / creds.count;
};
console.log(findAverage(data)); // 8.25
Kết quả
8.25
Giải thích: Chỉ 4 đối tượng đầu có Age khác null. Tổng Level = 8+9+5+11 = 33. Trung bình = 33 / 4 = 8.25. Các đối tượng có Age: null bị bỏ qua nhờ điều kiện if (Age).