Reorder array compared to another array in Swift [duplicate]

You can sort objects in order to follow the order in ids writing

let sorted = objects.sort { ids.indexOf($0.id) < ids.indexOf($1.id) }
// [{id "1"}, {id "2"}, {id "3"}]

Another example

let ids: [String] = ["3", "2", "1"]
let objects: [MyObject] = [MyObject(id: "3"), MyObject(id: "1"), MyObject(id: "2")]

let sorted = objects.sort { ids.indexOf($0.id) < ids.indexOf($1.id) }
// [{id "3"}, {id "2"}, {id "1"}]

This code is in Swift 2.2


Swift 4.2 solution

let sorted = objects.sorted { ids.index(of: $0.id)! < ids.index(of: $1.id)! }

Leave a Comment