Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove multiple indices from array

Tags:

swift

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 indices 1,4,5 from arr?

like image 401
rosewater Avatar asked Apr 28 '15 03:04

rosewater


People also ask

How do you delete multiple indexes in an array?

Approach 1: Store the index of array elements into another array which need to be removed. Start a loop and run it to the number of elements in the array. Use splice() method to remove the element at a particular index.

How do I remove multiple indexes from a list?

Remove Multiple elements from list by index range using del. Suppose we want to remove multiple elements from a list by index range, then we can use del keyword i.e. It will delete the elements in list from index1 to index2 – 1.

How do you remove an index from an array?

Combining indexOf() and splice() Methods Pass the value of the element you wish to remove from your array into the indexOf() method to return the index of the element that matches that value in the array. Then make use of the splice() method to remove the element at the returned index.


2 Answers

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 }
like image 126
Casey Fleser Avatar answered Sep 18 '22 07:09

Casey Fleser


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.

like image 37
Vatsal Manot Avatar answered Sep 21 '22 07:09

Vatsal Manot