How to efficiently sort an array of objects in reverse order?

Suppose I have an array of dictionaries:

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

How can I sort this so that it is 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 this is wrong and inefficient.

+4
source share
4 answers

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

let arr = [["id": 2], ["id": 59], ["id": 31]]
let sortedArr = arr.sort { Int($0["id"]!) > Int($1["id"]!) }
+3
source

I don't know if this is the fastest or the best, but swift provides a method sortthat takes clojure as an argument. You can write something like this:

var ordered = arrdict.sort { (dic1, dic2) -> Bool in
    dic1["id"] > dic2["id"]
}

Or compact:

var ordered = arrdict.sort { $0["id"] > $1["id"] }

$0..x clojure.
sort Apple :

( , ).

: (func <), Comparable - .

0

, sort, dictionary .

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

. .

let sortedArr = arr.sort { Int($0["id"]!) > Int($1["id"]!) }
0
    var val = [ { "id": 2 }, { "id": 59 }, { "id": 31 }];
var a = new Array();


for (i = 0; i < val.length; i++) { 
    document.write(Object.keys(val[i]).map(function (key) {return val[i][key]})+"<br>");
    a.push(Object.keys(val[i]).map(function (key) {return val[i][key]}));
}
a.sort();

var result = new Array();
for (i = 0; i < val.length; i++) { 
result.push({"id": a[i]});
}
0

All Articles