Created
September 20, 2016 10:31
-
-
Save alekseypotapov-dev/111d53f7325c209282e6ce4e2111a5db to your computer and use it in GitHub Desktop.
Group Array of Arrays by parameter
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 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's work perfect with struct but not woking with array of custom class
Any solution?