0

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

1
  • Are you manipulating only Swift Dictionaries, or do you have a model/custom struct? Is the finial order important? If yes, what's the logic? Commented Dec 13, 2022 at 18:20

1 Answer 1

2

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)]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.