Remove multiple indices from array

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

    Remove elements using indexes array:

    1. Array of Strings and indexes

      let animals = ["cats", "dogs", "chimps", "moose", "squarrel", "cow"]
      let indexAnimals = [0, 3, 4]
      let arrayRemainingAnimals = animals
          .enumerated()
          .filter { !indexAnimals.contains($0.offset) }
          .map { $0.element }
      
      print(arrayRemainingAnimals)
      
      //result - ["dogs", "chimps", "cow"]
      
    2. Array of Integers and indexes

      var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
      let indexesToRemove = [3, 5, 8, 12]
      
      numbers = numbers
          .enumerated()
          .filter { !indexesToRemove.contains($0.offset) }
          .map { $0.element }
      
      print(numbers)
      
      //result - [0, 1, 2, 4, 6, 7, 9, 10, 11]
      



    Remove elements using element value of another array

    1. Arrays of integers

      let arrayResult = numbers.filter { element in
          return !indexesToRemove.contains(element)
      }
      print(arrayResult)
      
      //result - [0, 1, 2, 4, 6, 7, 9, 10, 11]
      
    2. Arrays of strings

      let arrayLetters = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
      let arrayRemoveLetters = ["a", "e", "g", "h"]
      let arrayRemainingLetters = arrayLetters.filter {
          !arrayRemoveLetters.contains($0)
      }
      
      print(arrayRemainingLetters)
      
      //result - ["b", "c", "d", "f", "i"]
      
    0 讨论(0)
  • 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
            }
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题