You can extend Collection
, constrain its Element
to Equatable
protocol and create a computed property to return the grouped elements using reduce(into:)
method. You just need to check if there is a last element on the last collection equal to the current element and append the current element to the last collection if true otherwise append a new collection with it:
extension Collection where Element: Equatable {
var grouped: [[Element]] {
return reduce(into: []) {
$0.last?.last == $1 ?
$0[$0.index(before: $0.endIndex)].append($1) :
$0.append([$1])
}
}
}
let array = ["1","1","1","2","2","1","1"]
let grouped = array.grouped
print(grouped) // "[["1", "1", "1"], ["2", "2"], ["1", "1"]]\n"
solved How to group Arrays [duplicate]