Remove multiple indices from array

后端 未结 8 2161
一整个雨季
一整个雨季 2020-12-30 12:31

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

8条回答
  •  醉话见心
    2020-12-30 13:33

    The problem with flatmap is that it gives incorrect results if your array contains optionals.

    The following is much faster than the functional style solutions provided and works with optionals. You just have to make sure rmIndices is sorted and unique. It's also fairly language agnostic.

     var numRemoved: Int = 0
     for index in rmIndices {
         let indexToRemove = index - numRemoved
         arr.remove(at: indexToRemove)
         numRemoved += 1
     }
    

    If you need to make sure rmIndices is sorted and unique:

     rmIndices = Set(rmIndices).sorted()
    

    Using XCTest to remove 500 elements (including the operation to ensure uniqueness and sorted):

    0.006 sec

    vs.

    arr.enumerated().filter({ !rmIndices.contains($0.0) }).map { $0.1 }:

    0.206 sec

    I use this as an extension on Array

    extension Array {
    
        mutating func remove(at indices: [Int]) {
            let rmIndices = Set(indices).sorted()
            var numRemoved: Int = 0
            for index in rmIndices {
                let indexToRemove = index - numRemoved
                self.remove(at: indexToRemove)
                numRemoved += 1
            }
        }
    
    }
    

提交回复
热议问题