【问题标题】:Swift - comparing 2 arrays by id, and merge into new sorted ArraySwift - 按 id 比较 2 个数组,并合并到新的排序数组中
【发布时间】:2018-04-21 01:57:55
【问题描述】:

我有 2 个数组:

Arr1 = [ ["name": "Player1", "userId": "11", "Score": 9, "picURL": "https://1111"], ["name": "Player2", "userId": "12", "Score": 6, "picURL": "https://2222"], ["name": "Player3", "userId": "13", "Score": 4, "picURL": "https://3333"], ["name": "Player4", "userId": "14", "Score": 8, "picURL": "https://4444"],  ["name": "Player5", "userId": "15", "Score": 1, "picURL": "https://5555"] ]
Arr2 = [["userId": "12"], ["userId": "13"], ["userId": "15"]]

如何按“userId”映射此数组,以得到按“分数”按降序排序的数组,如下所示:

resultArr = [["name": "Player2", "Score": 6, "picURL": "https://2222], ["name": "Player3", "Score": 4, "picURL": "https://3333], ["name": "Player5", "Score": 1, "picURL": "https://5555] ]

【问题讨论】:

    标签: arrays swift sorting mapping


    【解决方案1】:
    let result = Arr1.filter { player in Arr2.contains(where: { $0["userId"] == player["userId"] as? String }) }
                     .sorted(by: { $0["Score"] as! Int > $1["Score"] as! Int })
    

    【讨论】:

    • 太棒了!谢谢!
    【解决方案2】:

    您可以先将 Arr1 更改为数组字典,以便以后更快地搜索,然后使用 Arr2 过滤该字典,然后再使用排序对过滤后的数组进行排序。

    let Arr1 = [ ["name": "Player1", "userId": "11", "Score": 9, "picURL": "https://1111"], ["name": "Player2", "userId": "12", "Score": 6, "picURL": "https://2222"], ["name": "Player3", "userId": "13", "Score": 4, "picURL": "https://3333"], ["name": "Player4", "userId": "14", "Score": 8, "picURL": "https://4444"],  ["name": "Player5", "userId": "15", "Score": 1, "picURL": "https://5555"]]
    
    // reducing array of dictionaries to dictioonary of array
    let dict = Arr1.reduce([String: [String:Any]]()) { (dict, arrayElement) -> [String: [String:Any]] in
        var dict = dict
        let userId = arrayElement["userId"] as! String
        var arrayElement = arrayElement
        arrayElement.removeValue(forKey: "userId")
        dict[userId] = arrayElement
        return dict
    }
    
    let Arr2 = [["userId": "12"], ["userId": "13"], ["userId": "15"]]
    
    // Using flat map to create an array of dictionaries where userid exists in Arr2 and then sorting that array on Score
    let filtered = Arr2.flatMap { (element) -> [String:Any]? in
        guard let userId = element["userId"] else {
            return nil
        }
        return dict[userId]
        }.sorted { (d1, d2) -> Bool in
            return d1["Score"] as! Int > d2["Score"] as! Int
    }
    
    print(filtered) // [["name": "Player2", "Score": 6, "picURL": "https://2222"], ["name": "Player3", "Score": 4, "picURL": "https://3333"], ["name": "Player5", "Score": 1, "picURL": "https://5555"]]
    

    【讨论】:

    • 感谢您的解决方案!
    猜你喜欢
    • 2010-10-15
    • 1970-01-01
    • 2023-03-14
    • 2015-08-21
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多