I have an array and I want to remove a bunch of indices
var arr = [0,1,2,3,4,5,6]
var rmIndices = [1,4,5]
What is the best way to remove in
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 }
Using lodash https://lodash.com/
var arr = [0,1,2,3,4,5,6]
var rmIndices = [1,4,5]
_.pullAt(arr, rmIndices);
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))
For Swift 3
var arr = [0,1,2,3,4,5,6]
let rmIndices = [1,4,5]
arr = arr.filter{ !rmIndices.contains($0) }
print(arr)
if you want to produce output very fastly then you can use
var arr = [0,1,2,3,4,5,6]
let rmIndices = [1,4,5]
arr = Array(Set(arr).subtracting(rmIndices))
print(array)
But it will change order of your array
In Swift 4:
let newArr = arr.enumerated().compactMap {
rmIndices.contains($0.0) ? nil : $0.1
}
enumerated()
generates (index, value) pairscompactMap
concatenates non-nil values$0.0
is the index (first element of enumerated pair) as $0.1$ is the valuecompactMap
gathers values whose indices are not found in rmIndices
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.