Most of the answers so far will have poor performance on large arrays.
The Array.contains(_:)
method has O(n)
performance, meaning that combining 2 arrays will have O(n•m)
performance (where n
is the number of items in one array and m
is the number of items in the other array.) This the time performance will deteriorate exponentially as the arrays grow in size.
If you only need to deal with a handful of items, this doesn't matter. But with >= hundreds of items in the arrays the time performance will get bad fast.
Better to use Sets:
let list1 = ["James","John","fat","cart"]
var list2 = ["James","fat","bobby"]
list2 = Array(Set(list1).union(Set(list2)))
print(Set([list1, list2]))
print(list2)
Sets use hashes for contains/uniqueness testing, which runs in ≈ constant time.
Jorgandar's answer should have good time-performance as well, but mine is a little simpler and (I think) more straightforward to understand.
I just convert each array into a Set
, combine them with Set.union(_:)
, and then convert the results back to a set.
If preserving the original order is important then you could build sets out of each array for uniqueness testing and then loop through one of the arrays using the sets to tell if each item needs to be added to the other array. That would be a little more complex but should give ≈O(n)
performance and preserve array ordering.