假设我们有一个这样的对象数组-
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函数来计算所有年龄属性为真值的对象的平均水平
让我们为该函数编写代码-
以下是代码-
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