Created
May 16, 2016 21:42
-
-
Save zoejessica/8ca911a738f0d79f41affd7bcd98084b to your computer and use it in GitHub Desktop.
Chunk an array into subarrays
This file contains 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 chunk<T : Equatable>(by valueToCompare: (Element) -> T) -> [[Element]] { | |
var currentValue = self[0] | |
var startIndex = 0 | |
var splits = [[Element]]() | |
for (index, value) in self.enumerate() { | |
if valueToCompare(value) != valueToCompare(currentValue) { | |
let newSplit = self[startIndex..<index] | |
splits.append(Array(newSplit)) | |
startIndex = index | |
currentValue = value | |
} | |
} | |
let newSplit = self[startIndex..<self.count] | |
splits.append(Array(newSplit)) | |
return splits | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment