Nibin V Nibin V - 2 months ago 34
Swift Question

Compare and return a distinct swift array object based on a property

I have an array of objects with some properties.

Ex: Restaurants {name, latitude, longitude, address}

I want to compare each object based on a particular property and return a list of distinct objects.

For example:

Array = [R1, R2, R3, R4, R5]


Let say, Restaurants R4 and R5 are closer to each other and they have the same latitude and longitude.

I need to compare and filter the array

($0.latitude == $1.latitude and $0.longitude == $1.longitude)
rounded to 3 decimal points

so that the final result will have the following items
[R1, R2, R3, R4]

Answer
class B {
    var a: String?
    var b: Int?
}

var arr:[B] = []

arr.filter{ index in
    var repeatedCount = 0
    arr.forEach{
        repeatedCount += $0.a == index.a ? 1 : 0
    }
    return repeatedCount == 1
}

The above solution will work but the complexity is o(arr.count^2) which is bad for large sets of items.

You can generalize the algorithm and make it efficient. Or make a extension function on Array distinct

In your case the code would be something like this:

arr.filter{ index in
    var repeatedCount = 0
    arr.forEach{
        if $0.latitude == index.latitude && $0.longitude == index.longitude {
            repeatedCount += 1
        }
    }
    return repeatedCount == 1
}