javascript - 使用 .reduce 为每个名字求和点

标签 javascript sum grouping reduce

我有一个这样的对象数组:

var array = [{name: "john", points: 20},
           {name: "jack", points: 12},
           {name: "john", points: 10},
           {name: "jack", points: 2},
           {name: "bill", points: 4}]

从这个数组中,我想生成一个新数组,其中包含每个名称的点的总和,通常是这样的:

var newArray = [{name: "john", points:30},
                {name: "jack", points:14},
                {name: "bill", points:4}]

我编写了以下功能,效果很好。

function filterArray(array){
    var newArray=[]
    for (i in array){
        var index=newArray.map(x=>x.name).indexOf(array[i].name)
        if (index==-1){
            newArray.push(array[i])
        }
        else{
            newArray[index].points+=array[i].points 
        }
    }
    return newArray;
    }

但是,我想使用一些可能更优雅的东西,比如 .reduce() 函数。有人知道怎么做吗?

最佳答案

您可以使用函数 reduce 进行分组,使用函数 Object.values 提取值。

let array = [{name: "john", points: 20},{name: "jack", points: 12},{name: "john", points: 10},{name: "jack", points: 2},{name: "bill", points: 4}],
    result = Object.values(array.reduce((a, {name, points}) => {
      (a[name] || (a[name] = {name, points: 0})).points += points;
      return a;
    }, Object.create(null)));
    
console.log(result);
.as-console-wrapper { min-height: 100%; }

关于javascript - 使用 .reduce 为每个名字求和点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55840432/

相关文章:

Javascript: "if"表单获取值为 "on"

javascript - 如何访问表中的值

php - MySQL - 一个表中的一列与另一个表中的另一列的总和

java - 如何在 Java 中使用枚举

javascript - 设置拖放子节点以在表格中显示json数组

javascript - 有什么方法可以匹配某个字符之前或之后的模式吗?

python - 尝试使用 Python/pandas 根据另一个数据帧的列的内部总和创建新的数据帧

r - 累计和滞后

sql - 在 postgresql 中进行分组的嵌套聚合函数

php - 使用 PHP 显示来自 MySQL 的分组地址数据