Skip to content

Instantly share code, notes, and snippets.

@raybellis
Created November 16, 2022 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raybellis/43c891a2d7af78311e07659634954c9f to your computer and use it in GitHub Desktop.
Save raybellis/43c891a2d7af78311e07659634954c9f to your computer and use it in GitHub Desktop.
A Swift extension to find the most common (modal) value among an array of (hashable) values
extension Array where Element : Hashable {
func modalValue() -> Self.Element? {
// populate a dictionary of element vs count
var dict: [Self.Element : Int] = [:]
self.forEach { v in
if let count = dict[v] {
dict[v] = count + 1
} else {
dict[v] = 1
}
}
// find the maximum count, and then return the first key that has that count
if let max = dict.values.max() {
for kv in dict {
if kv.value == max {
return kv.key
}
}
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment