There are actually a couple of difficulties with this operation. First off, there's a difference between the two things you could be asking for: either "difference" or "subtraction". Difference would return the elements that aren't in both arrays, so for instance:
let fruitsArray = ["apple", "mango", "blueberry", "orange"]
let vegArray = ["tomato", "potato", "mango", "blueberry"]
difference(fruitsArray, vegArray) // ["apple", "orange", "tomato", "blueberry"]
That doesn't seem to be what you're asking for, but it's worth bearing in mind.
The second is a "subtraction", which would yield your expected result. There's one more thing to bear in mind about this. The obvious one-liner:
fruitsArray.filter{ !vegArray.contains($0) }
// ["apple", "orange"]
Is quadratic. No issue if performance isn't important, but it's easily avoidable, using a Set
. Now, you could convert both, and use the normal Set
methods, but that's unnecessary. Converting to a Set
is O(n) (I think, I'm not actually sure), but you're going to have to iterate through the set from fruitsArray
anyway, and convert it back to an array in the end. The only advantage of a Set
is that is has an O(1) contains
method - so you only need to convert the this that you're using contains
on. The most efficient way, I think, is:
let vSet = Set(vegArray)
fruitsArray.filter { m in !vSet.contains(m) }