Skip to content

Instantly share code, notes, and snippets.

@pitiphong-p
Created August 14, 2016 18:09
Show Gist options
  • Save pitiphong-p/6db97dd723759bd72d5fa75b70474682 to your computer and use it in GitHub Desktop.
Save pitiphong-p/6db97dd723759bd72d5fa75b70474682 to your computer and use it in GitHub Desktop.
A simple method for grouping elements with given key calculating closure in Swift 3
extension Array {
func group<Key: Hashable>(by: (Element) -> Key) -> [Key: [Element]] {
var values = [Key: [Element]]()
let keys = self.map(by)
let pairs = zip(keys, self)
pairs.forEach { (key, value) in
var valuesOfKeys = values[key] ?? []
valuesOfKeys.append(value)
values[key] = valuesOfKeys
}
return values
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment