Ordering a list by frequency in Swift
I have a list of items that I want order by frequency, so that
var entries = ["one", "three", "one", "two", "one", "two"]
becomes
["one", "two", "three"]
I used the Swift dictionary grouping to do it:
extension Sequence where Element : Hashable {
func byFrequency() -> [Element] {
Dictionary(grouping: self, by: {$0}).sorted{ (a, b) in
a.value.count > b.value.count
}.map { $0.key}
}
}
entries.byFrequency()
gives
["one", "two", "three"]