Remove multiple indices from array

rmIndices.sort({ $1 < $0 })     

for index in rmIndices
{
    arr.removeAtIndex(index)
}

Note that I've sorted the indices in descending order. This is because everytime you remove an element E, the indices of the elements beyond E reduce by one.


Rather than a list of indices to remove, it may be easier to have a list of indices to keep, which you can do using the Set type:

let rmIndices = [1,4,5]
let keepIndices = Set(arr.indices).subtract([1,4,5])

Then you can use PermutationGenerator to create a fresh array of just those indices:

arr = Array(PermutationGenerator(elements: arr, indices: keepIndices))

Note that PermutationGenerator is going away in Swift 3 and also doesn't keep the ordering the same, though perhaps it did at one time. Using the accepted answer results in [2, 6, 0, 3] which may be unexpected. A couple of alternative approaches that give the expected result of [0, 2, 3, 6] are:

let flatArr = arr.enumerate().flatMap { rmIndices.contains($0.0) ? nil : $0.1 }

or

let filterArr = arr.enumerate().filter({ !rmIndices.contains($0.0) }).map { $0.1 }

Tags:

Swift