Skip to content

Instantly share code, notes, and snippets.

@nikriek
Last active July 24, 2017 12:25
Show Gist options
  • Save nikriek/1e1a3b7b694a420040030289e194641b to your computer and use it in GitHub Desktop.
Save nikriek/1e1a3b7b694a420040030289e194641b to your computer and use it in GitHub Desktop.
Functional Reduce By Key
extension Array {
/// GroupBy that puts each element into a group of similiar elements denoted by an Equatable attribute, complexity: O(n)
func reduce<G: Equatable>(by key: (Element) -> (G)) -> [G: [Element]] {
return reduce([:], { (result, element) in
var groups = result
let group = key(element)
if let existingGroupElements = groups[group] {
groups[group] = existingGroupElements + [element]
} else {
groups[group] = [element]
}
return groups
})
}
}
struct Post {
var title: String
var author: String
}
let posts = [
Post(title: "Post 1", author: "Peter Parker"),
Post(title: "Post 3", author: "Clark Kent"),
Post(title: "Post 2", author: "Peter Parker")
]
let postsByAuthor = posts.reduce(by: { $0.author })
/*
postsByAuthor:
[
"Peter Parker": [
Post(title: "Post 1", author: "Peter Parker"),
Post(title: "Post 2", author: "Peter Parker")
],
"Clark Kent": [
Post(title: "Post 3", author: "Clark Kent")
]
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment