Created
December 12, 2018 16:17
-
-
Save victorBaro/828dcd756f92f70db8215a450fd15a5e to your computer and use it in GitHub Desktop.
Array extension for grouping its values
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 grouped<T: Equatable>(by value: (Element) -> T) -> [[Element]] { | |
var result = [[Element]]() | |
for element in self { | |
var foundIndex: Int? | |
for (index, internalArray) in result.enumerated() { | |
if let firstValue = internalArray.first, value(firstValue) == value(element) { | |
foundIndex = index | |
continue | |
} | |
} | |
foundIndex == nil ? result.append([element]) : result[foundIndex!].append(element) | |
} | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Examples
intsGrouped:
[[1, 1], [2, 2], [3, 3, 3, 3]]
datesGrouped:
[[2018-12-12 16:20:05], [2018-12-11 16:20:05, 2018-12-11 16:20:05]]