如何在swift中删除数组中的重复对象?

sycxhyv7  于 2022-12-17  发布在  Swift
关注(0)|答案(1)|浏览(188)

例如,我有这样一个数组:

[
        {
            "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
                }
            }
        
      }

但也许有比这更简单的方法

oaxa6hgo

oaxa6hgo1#

一个可能的解决方案是将数组与Dictionary(grouping:by:)分组,然后将mapValues与点的总和分组。
生成的字典[<name>:<points>]可以重新Map到Person示例

struct Person  {
    let name: String
    let points: Int
}

let people = [
    Person(name: "Daniel", points: 10),
    Person(name: "Ana", points: 20),
    Person(name: "Daniel", points: 40),
]

let result = Dictionary(grouping: people, by: \.name)
    .mapValues{ $0.reduce(0, {$0 + $1.points})} // ["Daniel":50, "Ana":20]
    .map(Person.init)
print(result) // [Person(name: "Daniel", points: 50), Person(name: "Ana", points: 20)]

相关问题