Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort an array of objects in reverse order efficiently?

Suppose I have an array of dictionaries:

[ { "id": 2 }, { "id": 59 }, { "id": 31 } ... ]

How can I sort this so that it's in descending order, sorted by "id"?

My initial approach is something like:

Loop through each element, find the biggest one, and put it into a new array. Then, remove that from the element. Repeat.

But I know that's wrong and not efficient.

like image 534
TIMEX Avatar asked Apr 20 '16 04:04

TIMEX


2 Answers

You can use the sort function in Swift. Something like this:

let arr = [["id": 2], ["id": 59], ["id": 31]]
let sortedArr = arr.sort { Int($0["id"]!) > Int($1["id"]!) }
like image 102
Ishan Handa Avatar answered Oct 29 '22 16:10

Ishan Handa


You have only need to use below code that will give you the sorted array using the sort because dictionary is also a collection class.

let sortedDict = wordDict.sort { $0.0 < $1.0 }
print("\(sortedDict)") // 

In above code you found the sorted Dictionary. For sorting Array you need to add below code.

let sortedArr = arr.sort { Int($0["id"]!) > Int($1["id"]!) }
like image 42
Maheshwar Ligade Avatar answered Oct 29 '22 17:10

Maheshwar Ligade