Removing objects from an array based on another array
The easiest way is by using the new Set
container (added in 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)
If you want to reassign the resulting set to arrayA
, simply create a new instance using the copy constructor and assign it to arrayA
:
arrayA = Array(intersection)
The downside is that you have to create 2 new data sets.
Note that intersect
doesn't mutate the instance it is invoked in, it just returns a new set.
There are similar methods to add, subtract, etc., you can take a look at them
I agree with Antonio's answer, however for small array subtractions you can also use a filter closure like this:
let res = arrayA.filter { !contains(arrayB, $0) }
Like this:
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"]
@francesco-vadicamo's answer in Swift 2/3/4+
arrayA = arrayA.filter { !arrayB.contains($0) }