如何使用javascript reduce函数计算满足特定条件的项目的平均值? [英] How to use javascript reduce function to calculate average of items meeting a specific condition?

查看:37
本文介绍了如何使用javascript reduce函数计算满足特定条件的项目的平均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下对象数组:

So assume I have the following array of objects:

var arr = [
  {"name": "John", "score": "8.8"},
  {"name": "John", "score": "8.6"},
  {"name": "John", "score": "9.0"},
  {"name": "John", "score": "8.3"},
  {"name": "Tom",  "score": "7.9"}
];

var count = 0;
var avgScore = arr.reduce(function (sum,person) {
  if (person.name == "John") {
    count+=1;
    return sum + parseFloat(person.score);
  }
  return sum;
},0)/count);

问题:有没有办法在不创建全局 count 变量的情况下计算John"的平均分数.理想情况下,计数应该在 arr.reduce 中的匿名函数内部.

Question: Is there a way way to calculate the average score for "John" without creating a global count variable. Ideally, the count would be internal to the anonymous function in the arr.reduce.

推荐答案

要避免全局变量,请使用标准解决方案,例如 IIFEs块作用域.但是,我猜您正在寻找一种避免可变计数器的方法.

To avoid global variables, use a standard solution like IIFEs or block scopes. However I guess you're looking for a way to avoid a mutable counter.

最简单的方法是事先删除所有其他人:

The simplest would be to drop all other persons beforehand:

var johns = arr.filter(function(person) {
  return person.name == "John";
});
var avgScore = johns.reduce(function (sum, person) {
  return sum + parseFloat(person.score);
}, 0) / johns.length;

但是你也可以使用一个count,它与对象中的总和一起传递:

But you can also use a count that is passed along with the sum in an object:

var stats = arr.reduce(function ({count, sum}, person) {
  return (person.name == "John")
    ? {count: count+1, sum: sum + parseFloat(person.score)}
    : {count, sum};
}, {count:0, sum:0})
var avgScore = stats.sum / stats.count);

(使用 ES6 对象属性简写和解构)

这篇关于如何使用javascript reduce函数计算满足特定条件的项目的平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆