Removing objects from an array based on another ar

2020-05-24 19:35发布

I have two arrays like this:

var arrayA = ["Mike", "James", "Stacey", "Steve"]
var arrayB = ["Steve", "Gemma", "James", "Lucy"]

As you can see, James and Steve match and I want to be able to remove them from arrayA. How would I write this?

9条回答
姐就是有狂的资本
2楼-- · 2020-05-24 20:17

matt and freytag's solutions are the ONLY ones that account for duplicates and should be receiving more +1s than the other answers.

Here is an updated version of matt's answer for Swift 3.0:

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)
    }
}
查看更多
何必那么认真
3楼-- · 2020-05-24 20:19

For smaller arrays I use:

/* poormans sub for Arrays */

extension Array where Element: Equatable {

    static func -=(lhs: inout Array, rhs: Array) {

        rhs.forEach {
            if let indexOfhit = lhs.firstIndex(of: $0) {
                lhs.remove(at: indexOfhit)
            }
        }
    }

    static func -(lhs: Array, rhs: Array) -> Array {

        return lhs.filter { return !rhs.contains($0) }
    }
}
查看更多
混吃等死
4楼-- · 2020-05-24 20:27

Using the Array → Set → Array method mentioned by Antonio, and with the convenience of an operator, as freytag pointed out, I've been very satisfied using this:

// Swift 3.x/4.x
func - <Element: Hashable>(lhs: [Element], rhs: [Element]) -> [Element]
{
    return Array(Set<Element>(lhs).subtracting(Set<Element>(rhs)))
}
查看更多
登录 后发表回答