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
asked Dec 13, 2022 at 18:09
user20459409user20459409
-
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?Larme– Larme2022年12月13日 18:20:37 +00:00Commented Dec 13, 2022 at 18:20
1 Answer 1
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)]
answered Dec 13, 2022 at 18:30
Comments
lang-swift