Reputation: 1581
I have one empty array and two arrays with data
var resultsArray = [String]()
var array1 = ["1","2","2","3","4"]
var array2 = ["1","2","2","3","4","5","6"]
My goal is to append the resultsArray
with the elements from array2
that don't match array1
("5" and "6" in the example).
What's the subtlest way to do so?
Thank you.
Upvotes: 2
Views: 11739
Reputation: 285059
Use the filter
function
var resultsArray = [String]()
let array1 = ["1","2","2","3","4"]
let array2 = ["1","2","2","3","4","5","6"]
let filteredArray = array2.filter{ !array1.contains($0) }
resultsArray.appendContentsOf(filteredArray)
If the collections contain unique items consider to use Set
rather than Array
Update Swift 5.1:
In iOS 13, macOS 10.15 there is a new API in Array
public func difference<C>(from other: C) -> CollectionDifference<Element> where C : BidirectionalCollection, Self.Element == C.Element
var resultsArray = [String]()
let array1 = ["1","2","2","3","4"]
let array2 = ["1","2","2","3","4","5","6"]
let diff = array2.difference(from: array1)
resultsArray.append(contentsOf: array1)
for change in diff {
switch change {
case .remove(let offset, _, _): resultsArray.remove(at: offset)
case .insert(let offset, let element, _): resultsArray.insert(element, at: offset)
}
}
Upvotes: 21
Reputation: 1200
var resultsArray: [String] = []
let arrayX = ["1","2","2","3","4"]
let arrayY = ["1","2","2","3","4","5","6","7"]
let setX = Set(arrayX), setY = Set(arrayY)
resultsArray.append(contentsOf: setY.subtracting(setX))
This answer is faster than using filter.
Upvotes: 2
Reputation: 469
Use filter function for the purpose to find the different number of elements in the both array
let Filter = array2.filter{!array1}
resultArray.appendContentsof(Filter)
Upvotes: 0