Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

swift

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.
like image 439
Rob Zombie Avatar asked Dec 26 '22 05:12

Rob Zombie


1 Answers

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)
like image 159
Chris Wagner Avatar answered Apr 06 '23 01:04

Chris Wagner