How do I check in Swift if two arrays contain the same elements regardless of the order in which those elements appear in?

Gerwazy Sokołowski picture Gerwazy Sokołowski · Apr 19, 2016 · Viewed 47k times · Source

Let's say there are two arrays...

var array1 = ["a", "b", "c"]
var array2 = ["b", "c", "a"]

I'd like the result of the comparison of these two arrays to be true, and the following...

var array1 = ["a", "b", "c"]
var array2 = ["b", "c", "a", "d"]

...to be false. How can I achieve that in Swift? I tried to convert both arrays to sets but for some reason Set() keeps removing some (usually duplicated) objects that the array contains.

Any help would be appreciated.

Answer

Alexander Doloz picture Alexander Doloz · Apr 19, 2016

Swift 3, 4

extension Array where Element: Comparable {
    func containsSameElements(as other: [Element]) -> Bool {
        return self.count == other.count && self.sorted() == other.sorted()
    }
}

// usage
let a: [Int] = [1, 2, 3, 3, 3]
let b: [Int] = [1, 3, 3, 3, 2]
let c: [Int] = [1, 2, 2, 3, 3, 3]

print(a.containsSameElements(as: b)) // true
print(a.containsSameElements(as: c)) // false