Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder array compared to another array in Swift [duplicate]

I have one array in Swift containing some ids of objects, and I have another array containing these objects with their ids, so something like this:

class MyObject {
   let id: String
   ...
}

let ids: [String] = ...
let objects: [MyObject] = ...

Now the array of ids is sorted in some custom order, and I need the array of objects to be sorted in the same order. So for example:

let ids: [String] = ["1", "2", "3"]
let objects: [MyObject] = [obj3, obj1, obj2]
// obj1.id = "1"
// obj2.id = "2"
// obj3.id = "3"
objects.reorder(template: ids) 
// Now objects = [obj1, obj2, obj3]

So I basically need to implement this reorder method. Does anyone have a smart suggestion how to do this in Swift? I'm using Swift 3, so all the new APIs are available to me.

like image 241
Banana Avatar asked Mar 01 '26 08:03

Banana


2 Answers

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)! }
like image 95
Luca Angeletti Avatar answered Mar 02 '26 22:03

Luca Angeletti


A possible solution:

let sorted = objects.flatMap { obj in
    ids.index(of: obj.id).map { idx in (obj, idx) }
}.sorted(by: { $0.1 < $1.1 } ).map { $0.0 }

Explanation:

  • First, each object is tied to together with the corresponding position of the id in the array, this gives an array of (object, index) tuples.
  • This array is sorted with respect to the index positions.
  • Finally, the objects are extracted again.

Possible advantages:

  • Each object is searched only once in the array.
  • Objects for which no id exists in the array are ignored.
like image 20
Martin R Avatar answered Mar 02 '26 20:03

Martin R