Remove every nth element from swift array

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

(If you are using Swift 4.0 or below, use .flatMap instead of .compactMap. The .compactMap method was introduced in Swift 4.1 by SE-0187)

(If you are stuck with Swift 2, use .enumerate() instead of .enumerated().)


You can compute the new array directly from the old array by adjusting the indices. For n=3 it looks like this:

    0 1 2 3 4 5 6 7 8 ...    old array index
    | |   / /   / /
    | |  | |   / /
    | |  | |  / /
    | |  / / / / 
    0 1 2 3 4 5 6 ...        new array index

Code:

let thisArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let n = 3

let newCount = thisArray.count - thisArray.count/n
let newArray = (0..<newCount).map { thisArray[$0 + $0/(n - 1)] }

print(newArray) // [1, 2, 4, 5, 7, 8, 10]

After taking n-1 elements from the old array you have to skip one element. This is achieved by adding $0/(n - 1) to the (new) array index $0 in the map closure.


Since the Functional style solutions have already been posted I am using here an old fashion way approach

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

var filteredNums = [Double]()
for elm in nums.enumerate() where elm.index % 3 != 2 {
    filteredNums.append(elm.element)
}

Tags:

Arrays

Swift