Skip to content

Instantly share code, notes, and snippets.

@alekseypotapov-dev
Created September 20, 2016 10:31
Show Gist options
  • Save alekseypotapov-dev/111d53f7325c209282e6ce4e2111a5db to your computer and use it in GitHub Desktop.
Save alekseypotapov-dev/111d53f7325c209282e6ce4e2111a5db to your computer and use it in GitHub Desktop.
Group Array of Arrays by parameter
extension Array {
func groupBy<G: Hashable>(groupClosure: (Element) -> G) -> [[Element]] {
var groups = [[Element]]()
for element in self {
let key = groupClosure(element)
var active = Int()
var isNewGroup = true
var array = [Element]()
for (index, group) in groups.enumerate() {
let firstKey = groupClosure(group[0])
if firstKey == key {
array = group
active = index
isNewGroup = false
break
}
}
array.append(element)
if isNewGroup {
groups.append(array)
} else {
groups.removeAtIndex(active)
groups.insert(array, atIndex: active)
}
}
return groups
}
}
//Usage
struct User { var age = 0 }
let users: [User] = [User(age: 2), User(age: 4), User(age: 5), User(age: 5), User(age: 2)]
let groupedUser = users.groupBy { $0.age }
print(groupedUser)
@morteza2128
Copy link

It's work perfect with struct but not woking with array of custom class
Any solution?

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