Swift - 通过id比较2个数组,并合并到新的排序数组中

时间:2017-11-08 11:36:29

标签: arrays swift sorting mapping

我有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] ]

2 个答案:

答案 0 :(得分:1)

您可以先将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"]]

答案 1 :(得分: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 })