7

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.

TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • Possible duplicate of [Swift how to sort array of custom objects by property value](http://stackoverflow.com/questions/24130026/swift-how-to-sort-array-of-custom-objects-by-property-value) – Thilo Apr 20 '16 at 04:39
  • There's a ton of sort related information [here](http://stackoverflow.com/questions/24101718/swift-performance-sorting-arrays) – ryantxr Apr 20 '16 at 04:39

4 Answers4

6

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"]!) }
Ishan Handa
  • 2,271
  • 20
  • 25
1

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"]!) }
Maheshwar Ligade
  • 6,709
  • 4
  • 42
  • 59
0

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

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

Or compact:

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

The $0..x makes possible to access clojure arguments.
About sort algorithm Apple write:

Discussion The sorting algorithm is not stable (can change the relative order of elements that compare equal).

Requires: The less-than operator (func <) defined in the Comparable conformance is a strict weak ordering over the elements in self.

Andrea
  • 26,120
  • 10
  • 85
  • 131
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]});
}
jackinos
  • 84
  • 4