Created
January 7, 2021 18:45
-
-
Save MoussaHellal/e38667dc13cff7a4809f37c169c61e29 to your computer and use it in GitHub Desktop.
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
extension Sequence { | |
func group<GroupingType: Hashable>(by key: (Iterator.Element) -> GroupingType) -> [[Iterator.Element]] { | |
var groups: [GroupingType: [Iterator.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]! } | |
} | |
} | |
let arrayOfNumbers = [1, 1, 2, 3, 4, 5, 6, 7] | |
let groupedArray = arrayOfNumbers.group(by: {$0}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment