Oscar Apeland Oscar Apeland - 1 year ago 47
Swift Question

Reverse enumerate to filter out similar objects in an array

I have an array of

. My goal is to find the last position in the array with the same location as the following locations, then remove all the following objects.


[lat: 11.123, long: 11.123,
lat: 12.345, long: 123.123,
lat: 14.124, long: 14.124,
lat: 16.1661, long: 16.1616,
lat: 15.1515, long: 15.1515,
lat: 15.1515, long: 15.1515, //Remove
lat: 15.1515, long: 15.1515] //Remove

I would like to mutate the array they are stored in, instead of creating a new one.

My attempt so far:

var reversedLocations = Array(locations.reverse())
for (index,location) in reversedLocations.enumerate() {
if index+1 <= reversedLocations.count-1 {
let distanceToNext = LocationInterface.sharedInterface.distanceBetweenLocations(first: location, last: locations[index+1])
if distanceToNext < 10 {
toDate = reversedLocations.first!.timestamp

But this code is confusing, and I'm not sure its the best way to do it. The function is just a mess, as I mutate the array im enumerating so the index isn't correct. Are there any of the Array.reduce, .sort, .map or similar who can help me out with this one?

Answer Source
var locations = [1, 2, 3, 4, 5, 5, 5, 1, 2, 3, 4, 3, 3, 3]

while !locations.isEmpty && locations.dropLast().last == locations.last


Using Map, Reduce, or Filter is not necessary, in fact it would be recommended not to use them in this case. because you should stop reading all the elements once you find an element different from the last.

And like @Eendje said :

the other answers will also remove any other duplicates other than the last ones

The solution the OP used:

                while !locations.isEmpty && (LocationInterface.sharedInterface.distanceBetweenLocations(first: locations.dropLast().last!, last: locations.last!) > 15)