Created
April 18, 2019 11:29
-
-
Save TiagoBras/c4fc46d04cc6040df95675245b42fcd7 to your computer and use it in GitHub Desktop.
Group array by key with optional sorting
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
| import Foundation | |
| extension Array { | |
| func groupedBy<T: Hashable>(key: (Element) -> T, sort: ((Element, Element) -> Bool)? = nil) -> [T: [Element]] { | |
| var groups = [T: [Element]]() | |
| mainLoop: for element in self { | |
| let elementKey = key(element) | |
| if groups[elementKey] == nil { | |
| groups[elementKey] = [Element]() | |
| } | |
| if let sort = sort { | |
| for i in 0..<groups[elementKey]!.count { | |
| if sort(element, groups[elementKey]![i]) { | |
| groups[elementKey]!.insert(element, at: i) | |
| continue mainLoop | |
| } | |
| } | |
| } | |
| groups[elementKey]?.append(element) | |
| } | |
| return groups | |
| } | |
| } |
Author
TiagoBras
commented
Apr 18, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment