user5672373 user5672373 - 3 months ago 17
Swift Question

Remove every nth element from swift array

Is there an easy way to remove every nth element from a swift array. For example, in the array below:

thisArray = [2.0, 4.0, 3.0, 1.0, 4.5, 3.3, 1.2, 3.6, 10.3, 4.4, 2.0, 13.0]


If
n = 3
and start count from first element would like to return:

returnThis = [2.0, 4.0, 1.0, 4.5, 1.2, 3.6, 4.4, 2.0]

Answer
thisArray.enumerate().flatMap { index, element in index % 3 == 2 ? nil : element }
  • Use .enumerate() to attach the indices
  • Then use flatMap() to filter out items at indices 2, 5, 8, ... by returning nil, and strip the index for the rest by returning just element.