Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 - Difference between two arrays of dictionary

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?

like image 874
nouf Avatar asked May 02 '17 07:05

nouf


People also ask

What are the differences between arrays and dictionaries in Swift?

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.

What is the difference between an array and a dictionary?

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.

How do I check if two arrays are equal in Swift?

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 .

How do I check if all elements in an array are the same in Swift?

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.


1 Answers

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 }
}
like image 199
dilaver Avatar answered Oct 10 '22 11:10

dilaver