-2

How to group Arrays by a first same elements for example I have Array like that"

var Array = ["1","1","1","2","2","1","1"]

I want to group the Array like :

groupedArray = [
        ["1","1","1"],
        ["2","2"],
        ["1","1"]
    ]

Thank you!

Faris
  • 1,206
  • 1
  • 12
  • 18
  • 2
    What have you tried so far? What does your existing code look like? – ZGski Nov 21 '18 at 21:16
  • Iterate over all elements, keeping track of the current "run". When a run is complete add it to `groupedArray`. Don't forget to add the last run when the main iteration is done. – Steve Kuo Nov 21 '18 at 21:36

2 Answers2

2

Don't name your variable Array, you are masking the Swift.Array type and will cause untold number of weird bugs. Variable names in Swift should start with a lowercase letter.

Use prefix(while:) to gather identical elements starting from a specified index. And then you keep advancing that index:

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
}
Code Different
  • 90,614
  • 16
  • 144
  • 163
2

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"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571