Remove multiple indices from array

后端 未结 8 2096
一整个雨季
一整个雨季 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:11

    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 }
    
    0 讨论(0)
  • 2020-12-30 13:15

    Using lodash https://lodash.com/

    var arr = [0,1,2,3,4,5,6]
    var rmIndices = [1,4,5]
    _.pullAt(arr, rmIndices);
    
    0 讨论(0)
  • 2020-12-30 13:19

    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))
    
    0 讨论(0)
  • 2020-12-30 13:20

    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

    0 讨论(0)
  • 2020-12-30 13:20

    In Swift 4:

    let newArr = arr.enumerated().compactMap {
        rmIndices.contains($0.0) ? nil : $0.1
    }
    
    • enumerated() generates (index, value) pairs
    • compactMap concatenates non-nil values
    • In the closure, $0.0 is the index (first element of enumerated pair) as $0.1$ is the value
    • compactMap gathers values whose indices are not found in rmIndices
    0 讨论(0)
  • 2020-12-30 13:25
    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.

    0 讨论(0)
提交回复
热议问题