puks1978
puks1978

Reputation: 3697

How to remove all array items except at indexes at multiples of x - Swift

I have an array of coordinates (965 in total). I want to use these coordinates in Google Roads API however the limit is 100.

I have a function that determines how many items in the array and then gets the value to use.

round(Double(userCoordinatesHardCoded.count / 100))

produces 9.

I would like to remove ALL items that are not at indexes that are multiples of, in this case, 9. So in theory I will only ever have no more than 100 items in the array.

If possible, I would like to keep the first and last array item.

Upvotes: 1

Views: 1309

Answers (2)

Mark
Mark

Reputation: 12535

I know this has already been answered, but this is a great use case for using the filter function built into Swift:

let newCoordinates = oldCoordinates.filter { coord in
  return (coord % 9 != 0)
}

Upvotes: 1

Shamas S
Shamas S

Reputation: 7549

If space is not a problem, you can create another array with the desired multiples.

var oldCoordinates // Imagine it having all those elements
var newCoordinates : GoogleCoordinates = [] // This one will have new ones

newCoordinates.append(oldCoordinates[0])
var x = 1
for (x; x < oldCoordinates.count ; x++ ) {
   if (x % 5 == 0) {
      newCoordinates.append(oldCoordinates[x])
   }
}
if (x != (oldCoordinates.count - 1)) {
   newCoordinates.append(oldCoordinates[oldCoordinates.count - 1])
}

Upvotes: 0

Related Questions