我有两个数组
var array1 = new Array ["a", "b", "c", "d", "e"]
var array2 = new Array ["a", "c", "d"]
Run Code Online (Sandbox Code Playgroud)
我想从array1中删除array2的元素
Result ["b", "e"]
Run Code Online (Sandbox Code Playgroud)
jrc*_*jrc 81
@ 安东尼奥的解决方案是更好的性能,但这种保留排序,如果这是很重要的:
var array1 = ["a", "b", "c", "d", "e"]
let array2 = ["a", "c", "d"]
array1 = array1.filter { !array2.contains($0) }
Run Code Online (Sandbox Code Playgroud)
Ant*_*nio 57
最简单的方法是将两个数组转换为集合,从第一个数组中减去第二个数组,将结果转换为数组并将其分配回array1:
array1 = Array(Set(array1).subtracting(array2))
Run Code Online (Sandbox Code Playgroud)
请注意,您的代码无效Swift - 您可以使用类型推断来声明和初始化两个数组,如下所示:
var array1 = ["a", "b", "c", "d", "e"]
var array2 = ["a", "c", "d"]
Run Code Online (Sandbox Code Playgroud)
使用索引数组删除元素:
字符串和索引的数组
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"]
Run Code Online (Sandbox Code Playgroud)整数和索引的数组
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]
Run Code Online (Sandbox Code Playgroud)
使用另一个数组的元素值删除元素
整数数组
let arrayResult = numbers.filter { element in
return !indexesToRemove.contains(element)
}
print(arrayResult)
//result - [0, 1, 2, 4, 6, 7, 9, 10, 11]
Run Code Online (Sandbox Code Playgroud)字符串数组
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"]
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
19608 次 |
| 最近记录: |