How to group Arrays
本问题已经有最佳答案,请猛点这里访问。
如何按第一个相同的元素对数组进行分组
例如我有这样的数组"
1 | var Array = ["1","1","1","2","2","1","1"] |
我想将数组分组为:
1 2 3 4 5 | groupedArray = [ ["1","1","1"], ["2","2"], ["1","1"] ] |
谢谢!
您可以扩展
1 2 3 4 5 6 7 8 9 | 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]) } } } |
1 2 3 4 | let array = ["1","1","1","2","2","1","1"] let grouped = array.grouped print(grouped) //"[["1","1","1"], ["2","2"], ["1","1"]]\ " |
不要将变量命名为
使用
1 2 3 4 5 6 7 8 9 | let array = ["1","1","1","2","2","1","1"] var index = 0 var groupedArray = [[String]]() while index < array.count { let slice = array[index...].prefix(while: { $0 == array[index] }) groupedArray.append(Array(slice)) index = slice.endIndex } |