Skip to content

Instantly share code, notes, and snippets.

@wildthink
Created March 19, 2020 15:49
Show Gist options
  • Save wildthink/e383a2fa1191fd5ae43ca1ed255247de to your computer and use it in GitHub Desktop.
Save wildthink/e383a2fa1191fd5ae43ca1ed255247de to your computer and use it in GitHub Desktop.
Collection grouping with order preservation
// https://www.goranbrl.dev/posts/1-grouping/
extension Collection {
func groupBy<GroupingType: Hashable>(key: (Element) -> (GroupingType)) -> [[Element]] {
var groups: [GroupingType: [Element]] = [:]
var groupsOrder: [GroupingType] = []
forEach { element in
let key = key(element)
if case nil = groups[key]?.append(element) {
groups[key] = [element]
groupsOrder.append(key)
}
}
return groupsOrder.map { groups[$0] ?? [] }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment