2017-11-08 17 views
-1

idで2つの配列を比較すると、新しいソートされた配列にマージ:私は結果で並べ替え配列を取得するために「はuserId」によって、この配列をマッピングするにはどうすればよいスウィフト - 私は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"]] 

を「スコア」このような降順に:

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

答えて

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 }) 
+0

それは素晴らしいです!ありがとうございました! – Rurom

1

をあなたはより速く、後で検索し、次に濾過し、配列をソートするソート使用する前に、その辞書をフィルタリングするARR2を使用するために、最初のアレイの辞書にごARR1を変更することにより、それを達成することができます。

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"]] 
+0

あなたのソリューションのために、ありがとうございます! – Rurom

関連する問題