Created
November 16, 2022 22:39
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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