Skip to content

Instantly share code, notes, and snippets.

@zoejessica
Created May 16, 2016 21:42
Show Gist options
  • Save zoejessica/8ca911a738f0d79f41affd7bcd98084b to your computer and use it in GitHub Desktop.
Save zoejessica/8ca911a738f0d79f41affd7bcd98084b to your computer and use it in GitHub Desktop.
Chunk an array into subarrays
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