Home > Software engineering >  How to filter duplicated elements until a new one comes
How to filter duplicated elements until a new one comes

Time:12-09

I want to filter out the duplicated elements until a new element comes using Swift. and I want to do this for the whole array.

Example: [1,1,1,2,2,1]

Output: [1,2,1]

CodePudding user response:

You can use reduce(into:_:) to do so:

let array = [1,1,1,2,2,1]
let filtered = array.reduce(into: [Int]()) { partialResult, current in
    guard let last = partialResult.last else { partialResult.append(current); return }
    if last != current {
        partialResult.append(current)
    }
}
print(filtered)

We iterate over the array. partialResult is the current new array being populated. We check if there is already an initial value, else we add it. Then, we compare last value of the partialResult with current value iterated of the initial array to decide if we append it or not to partialResult

Once you understood the logic, it could also be written with:

let filtered2 = array.reduce(into: [Int]()) { partialResult, current in
    if partialResult.last != current {
        partialResult.append(current)
    }
}
print(filtered2)
  • Related