I have two arrays of dictionaries:
let arrayA = [["name1": "email1"], ["name2": "email2"]]
let arrayB = [["name1": "email1"], ["name3": "email3"]]
I want to compare them and get another two arrays: arrayC should have the elements in arrayA but not in arrayB, and arrayD should have the elements in arrayB but not in arrayA:
let arrayC = [["name2": "email2"]]
let arrayD = [["name3": "email3"]]
How can I do this taking into the consideration large arrays?
Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations. Arrays, sets, and dictionaries in Swift are always clear about the types of values and keys that they can store.
An array is just a sorted list of objects. A dictionary stores key-value pairs. There are no advantages or disadvantages, they are just two data structures, and you use the one you need.
To check if two arrays are equal in Swift, use Equal To == operator. Equal To operator returns a Boolean value indicating whether two arrays contain the same elements in the same order. If two arrays are equal, then the operator returns true , or else it returns false .
Swift has built-in way of checking whether all items in an array match a condition: the allSatisfy() method. Give this thing a condition to check, and it will apply that condition on all items until it finds one that fails, at which point it will return false.
Here you go
let arrayA = [["name1": "email1"], ["name2": "email2"]]
let arrayB = [["name1": "email1"], ["name3": "email3"]]
let arrayC = arrayA.filter{
let dict = $0
return !arrayB.contains{ dict == $0 }
}
let arrayD = arrayB.filter{
let dict = $0
return !arrayA.contains{ dict == $0 }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With