iOS swift从另一个数组中删除数组的元素

时间:2015-08-13 09:29:44

标签: ios arrays swift

我有两个数组

var array1 = new Array ["a", "b", "c", "d", "e"]
var array2 = new Array ["a", "c", "d"]

我想从array1中删除array2的元素

Result ["b", "e"]

7 个答案:

答案 0 :(得分:73)

@ Antonio's solution性能更高,但如果这很重要,这会保留排序:

var array1 = ["a", "b", "c", "d", "e"]
let array2 = ["a", "c", "d"]
array1 = array1.filter { !array2.contains($0) }

答案 1 :(得分:49)

最简单的方法是将两个数组转换为集合,从第一个数组中减去第二个数组,将结果转换为数组并将其分配回array1

array1 = Array(Set(array1).subtracting(array2))

请注意,您的代码无效Swift - 您可以使用类型推断来声明和初始化两个数组,如下所示:

var array1 = ["a", "b", "c", "d", "e"]
var array2 = ["a", "c", "d"]

答案 2 :(得分:8)

使用索引数组删除元素:

  1. 字符串和索引数组

    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. 整数和索引数组

    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]
    


  3. 使用其他数组的元素值删除元素

    1. 整数数组

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

      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"]
      

答案 3 :(得分:2)

您可以创建集合,然后使用减法方法

let setA = Set(arr1)
let setB = Set(arr2)
setA.subtract(set2)

答案 4 :(得分:2)

超出范围但如果它在这里它会帮助我。 从 OBJECTIVE-C

中的数组中删除subArray
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"not (self IN %@)", subArrayToBeDeleted];
NSArray* finalArray = [initialArray filteredArrayUsingPredicate:predicate];

希望它能帮助别人:)

答案 5 :(得分:1)

Shai Balassiano 答案的扩展版本:

extension Array where Element: Equatable {
  func subtracting(_ array: [Element]) -> [Element] {
      self.filter { !array.contains($0) }
  }

  mutating func remove(_ array: [Element]) {
      self = self.subtracting(array)
  }
}

答案 6 :(得分:0)

以下是@jrc答案的扩展名:

extension Array where Element: Equatable {
    func subtracting(_ array: Array<Element>) -> Array<Element> {
        self.filter { !array.contains($0) }
    }
}