从基于另一个数组的数组中删除对象

Hen*_*own 31 arrays xcode swift

我有两个像这样的数组:

var arrayA = ["Mike", "James", "Stacey", "Steve"]
var arrayB = ["Steve", "Gemma", "James", "Lucy"]
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,JamesSteve比赛,我希望能够从删除它们arrayA.我怎么写这个?

Fed*_*llo 51

@francesco-vadicamo在Swift 2/3/4 +中的回答

 arrayA = arrayA.filter { !arrayB.contains($0) }
Run Code Online (Sandbox Code Playgroud)


Ant*_*nio 31

最简单的方法是使用新Set容器(在Swift 1.2/Xcode 6.3中添加):

var setA = Set(arrayA)
var setB = Set(arrayB)

// Return a set with all values contained in both A and B
let intersection = setA.intersect(setB) 

// Return a set with all values in A which are not contained in B
let diff = setA.subtract(setB)
Run Code Online (Sandbox Code Playgroud)

如果要将结果集重新分配给arrayA,只需使用复制构造函数创建一个新实例并将其分配给arrayA:

arrayA = Array(intersection)
Run Code Online (Sandbox Code Playgroud)

缺点是您必须创建2个新数据集.请注意,intersect不会改变它所调用的实例,它只返回一个新集.

有类似的方法可以添加,减去等,你可以看看它们


mat*_*att 18

像这样:

var arrayA = ["Mike", "James", "Stacey", "Steve"]
var arrayB = ["Steve", "Gemma", "James", "Lucy"]
for word in arrayB {
    if let ix = find(arrayA, word) {
        arrayA.removeAtIndex(ix)
    }
}
// now arrayA is ["Mike", "Stacey"]
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案适用于小型阵列,但必须考虑到其复杂性为O(n ^ 2).对于较大的数组,我会考虑将`arrayA`转换为一个集合并将其用于`find` - 这应该将复杂度降低到O(2n) (11认同)

Fra*_*amo 14

我同意Antonio的回答,但是对于小数组减法,你也可以使用这样的过滤器闭包:

let res = arrayA.filter { !contains(arrayB, $0) }
Run Code Online (Sandbox Code Playgroud)


Rui*_*uiz 10

matt和freytag的解决方案是唯一可以解决重复问题的解决方案,并且应该比其他答案接收更多+ 1.

这是关于Swift 3.0的matt的答案的更新版本:

var arrayA = ["Mike", "James", "Stacey", "Steve"]
var arrayB = ["Steve", "Gemma", "James", "Lucy"]
for word in arrayB {
    if let ix = arrayA.index(of: word) {
        arrayA.remove(at: ix)
    }
}
Run Code Online (Sandbox Code Playgroud)


fre*_*tag 6

这也可以实现为减号:

func -<T:RangeReplaceableCollectionType where T.Generator.Element:Equatable>( lhs:T, rhs:T ) -> T {

    var lhs = lhs
    for element in rhs {
        if let index = lhs.indexOf(element) { lhs.removeAtIndex(index) }
    }

    return lhs
}
Run Code Online (Sandbox Code Playgroud)

现在你可以使用了

arrayA - arrayB
Run Code Online (Sandbox Code Playgroud)


Ami*_*aiB 5

使用Array ? Set ? ArrayAntonio 提到的方法,并借助操作员的便利,正如 freytag 指出的那样,我对使用此方法感到非常满意:

// Swift 3.x/4.x
func - <Element: Hashable>(lhs: [Element], rhs: [Element]) -> [Element]
{
    return Array(Set<Element>(lhs).subtracting(Set<Element>(rhs)))
}
Run Code Online (Sandbox Code Playgroud)