How to remove elements from an array that match elements in another array

How can I remove elements from an array that match elements in another array?

Suppose we have an array and we loop through it and figure out which elements to remove:

var sourceItems = [ ... ]
var removedItems = [SKShapeNode]()

for item : SKShapeNode in sourceItems {
    if item.position.y > self.size.height {
        removedItems.append(item)
        item.removeFromParent()
    }
}

sourceItems -= removedItems // well that won't work.

      

+3


source to share


2 answers


You can use the function filter

.

let a = [1, 2, 3]
let b = [2, 3, 4]

let result = a.filter { element in
    return !b.contains(element)
}

      

result

will be [1]

Or more succinctly ...



let result = a.filter { !b.contains($0) }

Check out the Swift standard library link

Or you can use type Set

.

let c = Set<Int>([1, 2, 3])
let d = Set<Int>([2, 3, 4])
c.subtract(d)

      

+7


source


Remember that if you use the Set parameter, your results will only be unique values ​​and will not maintain the initial order if that matters to you, whereas the array filter option will maintain the initial order of the array, at least what elements remain.

Swift 3



let c = Set<Int>([65, 1, 2, 3, 1, 3, 4, 3, 2, 55, 43])
let d = Set<Int>([2, 3, 4])
c.subtracting(d)

c = {65, 2, 55, 4, 43, 3, 1}
d = {2, 3, 4}
result = {65, 55, 43, 1}

      

0


source







All Articles