corban
corban

Reputation: 628

Compare elements in collection and remove by checking properties

I have got an array of elements from a specific class. I want to compare elements in order and remove them if the subsequent has equality in a specific property or is the last.

For example in an array of elements with different colors. I want to remove green elements at the end and green elements side by side.

I use a while loop for checking and asking if there is a better way in swift. I think maybe with reduce you could build a new array but would it be faster? Here is a code example.

struct Car {
    var color: UIColor
}

var someCars = [Car(color: .blue), Car(color: .green), Car(color: .green), Car(color: .yellow), Car(color: .blue), Car(color: .green)]

var ix:Int = someCars.count - 1
while ix >= 0 {
    if someCars[ix].color == .green && (ix == someCars.count - 1 || someCars[ix + 1].color == .green) {
        someCars.remove(at: ix)
    }
    ix -= 1
}

Upvotes: 1

Views: 68

Answers (1)

FilipD
FilipD

Reputation: 144

your method seems to be fast, being of O(n)

but readability might be improved perhaps. This might be easier, and also immediately removes all entries which have the same colour as the previous element. So it works for green, blue, etc.

var filtered:[Car] = []

someCars.forEach { (car) in

    if filtered.count == 0 {
        filtered.append(car)
    }

    if let last = filtered.last {
        if last.color != car.color {
            filtered.append(car)
        }
    }
}


//then, if needed remove the first and last entry if they are green
if let last = filtered.last, let first = filtered.first {
    if last.color == .green {
        filtered.removeLast()
    }
    if first.color == .green {
        filtered.removeFirst()
    }
}

Upvotes: 1

Related Questions