Swift 3 - Difference between two dictionary arrays

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 two more arrays: arrayC should have elements in arrayA, but not in arrayB, and arrayD should have elements in arrayB, but not in arrayA:

let arrayC = [["name2": "email2"]]
let arrayD = [["name3": "email3"]]

How can I do this given large arrays?

+4
source share
2 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 }
}
+7
source

I know that this answer can complicate the situation and that you can use a filter, but ... do you consider using Setsinstead Arrays?

setA, setB, setA setB .

.

. , , , .

:

  • Distinct:
  • : , , .

( ):

, , .

... - , .

... Email Hashable:

struct Email {
    let name: String
    let email: String
}

extension Email: Hashable {
    var hashValue: Int {
        return "\(name)\(email)".hashValue
    }

    static func ==(lhs: Email, rhs: Email) -> Bool {
         return lhs.name == rhs.name && lhs.email == rhs.email
    }
}

:

let arrayA = [Email(name: "name1", email: "email1"), Email(name: "name2", email: "email2")]
let arrayB = [Email(name: "name1", email: "email1"), Email(name: "name3", email: "email3")]
let setA = Set(arrayA)
let setB = Set(arrayB)

let inBothAAndB = setA.intersection(setB) //gives me an Email with "name1", "email1"
let inAButNotB = setA.subtracting(setB) //gives me an Email with "name2", "email2"
let inBButNotA = setB.subtracting(setA) //gives me an Email with "name3", "email3"

... , , , ( , ), ... , :)

, .

+3

Source: https://habr.com/ru/post/1676121/


All Articles