JavaScript - 排除平均值计算中的一些值
假设我们有一个类似以下的对象数组 -
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} ];
我们需要编写一个 JavaScript 函数,该函数计算所有 `age` 属性具有真值的对象的平均级别
让我们为这个函数编写代码 -
示例
以下是代码 -
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
广告