gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:03:50 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com