4

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

Assume we have an array and we loop through it and find 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.

2 Answers 2

10

You can use the filter function.

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 Reference

Or you can use the Set type.

let c = Set<Int>([1, 2, 3])
let d = Set<Int>([2, 3, 4])
c.subtract(d)
Sign up to request clarification or add additional context in comments.

5 Comments

Chris is there a mutating filter? That would remove itms from array instead of returning new array?
I don't believe so. What are your concerns with assigning the returned value to your reference?
Well, it's cheaper to avoid reallocating memory and reuse existing, but it seems that's not the case with swift arrays.
Ah yeah, I can't find anything on the topic. I am curious how the implementation would look as you're mutating what you're enumerating over, in a sense. NSMutableArray has a filter method that does just that however.
Previously in Swift 1.x we used !contains(b, element). Now in Swift 2.x we use !b.contains(element)
0

Be mindful if using the Set option, that your results only be unique values and will not maintain the initial ordering, if that matters to you, whereas the Array filter option will maintain the initial array's order, 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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.