gpt4 book ai didi

coffeescript - 在对象数组中,如何根据对象属性进行聚合?

转载 作者:行者123 更新时间:2023-12-04 05:06:48 25 4
gpt4 key购买 nike

假设我有以下对象数组:

dataArray = [ 
{ id: "a", score: 1 },
{ id: "b", score: 2 },
{ id: "c", score: 5 },
...
{ id: "a", score: 3 },
...
{ id: "c", score: 2},
...
]

如何获得如下所示的 resultArray:
resultArray = [
{ id: "a", score: sum of all the scores when id is a },
{ id: "b", score: sum of all the scores when id is b },
...
...
]

最佳答案

如果您使用下划线库:

_.map  _.groupBy(dataArray, 'id'), (v, k) -> 
{id: k, score: _.reduce(v, ((m, i) -> m + i['score']), 0) }

关于coffeescript - 在对象数组中,如何根据对象属性进行聚合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15441272/

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