Skip to content

Instantly share code, notes, and snippets.

@TiagoBras
Created April 18, 2019 11:29
Show Gist options
  • Select an option

  • Save TiagoBras/c4fc46d04cc6040df95675245b42fcd7 to your computer and use it in GitHub Desktop.

Select an option

Save TiagoBras/c4fc46d04cc6040df95675245b42fcd7 to your computer and use it in GitHub Desktop.
Group array by key with optional sorting
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
}
}
@TiagoBras
Copy link
Author

let groupedByParity = [1, 2, 3, 4, 5].groupedBy(key: { $0 % 2 == 0 }, sort: <)

// [false: [1, 3, 5], true: [2, 4]]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment