user20459409
user20459409

Reputation:

How to remove duplicate objects from array on swift?

I have for example this array:

[
        {
            "name": "Daniel",
            "points": 10,
        },
        {
            "name": "Ana",
            "points": 20
        },
        {
            "name": "Daniel",
            "points": 40
        }
    ]

And i want delete one "Daniel" and points to the sum of all whit the same name like this:

[
        {
            "name": "Daniel",
            "points": 50,
        },
        {
            "name": "Ana",
            "points": 20
        }
    ]

How can i transform it?

I was trying whit two bucles:

     for name in persons {

           for name2 in persons {
                if name == name2 {
                   //remove the duplicate one and sum his points
                }
            }
        
      }
        

but maybe there is a way too much easier than this one

Upvotes: 0

Views: 157

Answers (1)

vadian
vadian

Reputation: 285069

A possible solution is to group the array with Dictionary(grouping:by:) then mapValues to the sum of the points.

The resulting dictionary [<name>:<points>] can be remapped to Person instances

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)]

Upvotes: 2

Related Questions