Created
March 19, 2020 15:49
-
-
Save wildthink/e383a2fa1191fd5ae43ca1ed255247de to your computer and use it in GitHub Desktop.
Collection grouping with order preservation
This file contains hidden or 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
// 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