我正在尝试从数组中排除“ 0”值,以获得更好的平均结果。
我的数组是:[0,0,0,0,80,90,100,0]
function clacGPA(gradeData) {
var sum, avg = 0;
if (gradeData.length) {
sum = gradeData.reduce(function (a, b) {
return a + b;
});
avg = sum / gradeData.length;
}
document.getElementById('gpa').innerText = avg.toFixed(2);
}
My expected result should be:
avg = 80+90+100 / 3
答案 0 :(得分:2)
只需先过滤掉0个值:
clacGPA([0, 0, 0, 0, 80, 90, 100, 0]);
function clacGPA(gradeData) {
const filtered = gradeData.filter(item => item !== 0);
const sum = filtered.reduce((a, b) => a + b);
const avg = sum / filtered.length;
console.log(avg);
}
答案 1 :(得分:2)
您可以将函数reduce
与累加器一起使用,该累加器存储计数和总和。
let arr = [0, 0, 0, 0, 80, 90, 100, 0];
let result = arr.reduce((a, c) => {
if (c !== 0) {
a.count++;
a.sum += c;
}
return a;
}, {count: 0, sum: 0});
if (result.count) console.log(result.sum / result.count);