Let's say retrieve an array of objects from a JSON API:
[
{
"id": 48,
"name": "Bob"
},
{
"id": 198,
"name": "Dave"
},
{
"id": 2301,
"name": "Amy"
},
{
"id": 990,
"name": "Colette"
}
]
// e.g. for ease of reproduction:
let dataObjects = [
["id": 48, "name": "Bob"],
["id": 198, "name": "Dave"],
["id": 2301, "name": "Amy"],
["id": 990, "name": "Colette"]
]
On the client, I'd like to allow the user to re-order these objects. To save the order, I'll store a list of ids in an array:
let index: [Int] = [48, 990, 2103, 198]
How can I reorder the original array of data objects based on the order of ids in the sorting index?
dataObjects.sort({
// magic happens here maybe?
}
So that in the end, I get:
print(dataObjects)
/*
[
["id": 48, "name": "Bob"],
["id": 990, "name": "Colette"],
["id": 2301, "name": "Amy"],
["id": 198, "name": "Dave"]
]
/*