Tariq
Tariq

Reputation: 9979

How to remove duplicate items from an array with multiple criteria?

Objective: I have to delete object from array which has same title, vicinity, coordinate.latitude and coordinate.longitude

    class Place {
        var placeID: String?
        var title: String?
        var vicinity: String?
        var detailsUrl: String?
        var openingHours: OpeningHours?
        var position: [Double]

        var coordinate: CLLocationCoordinate2D {
          return CLLocationCoordinate2DMake(position.first ?? 0, position.last ?? 0)
    }

One way i have tried that -

extension Array {
    func removingDuplicates <T: Hashable>(byKey key: (Element) -> T) -> [Element] {
        var result = [Element]()
        var seen = Set<T>()
        for value in self {
            if seen.insert(key(value)).inserted {
                result.append(value)
            }
        }
        return result
    }
}


let array = list.removingDuplicates(byKey: { "\($0.coordinate.latitude)" + "\($0.coordinate.longitude)" + ($0.title ?? " ") + ($0.vicinity ?? " ") })

But i really don't like above solution. What is the most appropriate way to handle it ?

Upvotes: 0

Views: 174

Answers (1)

RajeshKumar R
RajeshKumar R

Reputation: 15758

Add Equatable to the Place class

class Place: Equatable {
    static func == (lhs: Place, rhs: Place) -> Bool {
        return lhs.title == rhs.title && lhs.vicinity == rhs.vicinity &&
            lhs.coordinate.latitude == rhs.coordinate.latitude && lhs.coordinate.longitude == rhs.coordinate.longitude
    }
    //...        
}

And filter the array elements with the place/places to delete

var list = [Place]()
//Delete multiple places
let placesToDelete = [Place]()
let result = list.removeAll { placesToDelete.contains($0) }
//Delete one place
let placeToDelete = Place()
let result = list.removeAll { $0 == placeToDelete }

Upvotes: 1

Related Questions