How to group array by property in Swift

Issue #510

Use Dictionary(grouping:by:)

1
2
3
4
5
6
7
8
9
10
func groups(countries: [Country]) -> [Group] {
let dictionary = Dictionary(grouping: countries, by: { String($0.name.prefix(1)) })
let groups = dictionary
.map({ (key: String, value: [Country]) -> Group in
return Group(initial: key, countries: value)
})
.sorted(by: { $0.initial < $1.initial })

return groups
}

Comments