簡體   English   中英

獲取基於特定鍵值對的唯一記錄列表

[英]Get list of unique records based on specific key, value pair

我是 swift 的新手,我想知道我是否可以根據 2 arrays 的鍵值對獲得唯一值。

數組 1:

let arr1 = [
   ["title" : "News", "icon" : "news_1"],
   ["title" : "Food", "icon" : "food_1"]
]

陣列 2:

let arr2 = [
   ["title" : "News", "icon" : "news_2"],
   ["title" : "Technology", "icon" : "tech_1"]
]

如何得到類似的結果

數組 3:

let arr3 = [
   ["title" : "Food", "icon" : "food_1"],
   ["title" : "Technology", "icon" : "tech_1"]
]

因此,我需要基於結果數組中名為“title”的鍵的 array-1 和 array-2 中所有唯一值的集合。

注意:這里我在 array-1 和 2 中有標題“食物”,但圖標不同。

您正在尋找的可能是這兩個 arrays 的對稱差異。但是正如評論中指出的那樣,您的數據結構不太適合這個。 如果你真的想堅持目前的結構,這可能對你有用:

func symmetricDifference(arrays: [[[String: String]]], by key: String) -> [[String: String]] {
    var result = [String: [String: String]?]()
    for array in arrays {
        for element in array {
            guard let keyValue = element[key] else {
                // Ignore elements that do not contain the key, adjust as needed
                continue
            }
            
            // Check if we already saw the value
            if !result.keys.contains(keyValue) {
                // Add the element
                result[keyValue] = element
            } else {
                // We saw this keyValue already, remove the element
                result.updateValue(nil, forKey: keyValue)
            }
        }
    }
    
    // Only return elements where value is not nil
    return result.values.compactMap { $0 }
}

// Usage
symmetricDifference(arrays: [arr1, arr2], by: "title")

通過使用更適合的數據結構,您可以輕松使用內置的 Set 運算符:

struct Category: Hashable {
    let title: String
    let icon: String
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(title)
    }
    
    static func ==(lhs: Category, rhs: Category) -> Bool {
        lhs.title == rhs.title
    }
}

let set1 = Set([Category(title: "News", icon: "news_1"), Category(title: "Food", icon: "food_1")])
let set2 = Set([Category(title: "News", icon: "news_2"), Category(title: "Technology", icon: "tech_1"), Category(title: "News", icon: "news_2")])
let result = set1.symmetricDifference(set2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM