例如,我有这样一个数组:
[
{
"name": "Daniel",
"points": 10,
},
{
"name": "Ana",
"points": 20
},
{
"name": "Daniel",
"points": 40
}
]
我想删除一个“丹尼尔”,并指向所有whit相同的名字的总和,像这样:
[
{
"name": "Daniel",
"points": 50,
},
{
"name": "Ana",
"points": 20
}
]
我该如何改变它?
我想用两桶钱:
for name in persons {
for name2 in persons {
if name == name2 {
//remove the duplicate one and sum his points
}
}
}
但也许有比这更简单的方法
1条答案
按热度按时间oaxa6hgo1#
一个可能的解决方案是将数组与
Dictionary(grouping:by:)
分组,然后将mapValues
与点的总和分组。生成的字典
[<name>:<points>]
可以重新Map到Person
示例