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.

2

4 Answers 4

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"]!) }
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Rage. What if It's not [String: Int], but instead it's a custom object (In my case, a message), and it has a property of "id" ?
just use $0.propertyName instead of $0["id"]. It should work fine.
check the link provided by Thilo. the gave the same link in comments for your question for custom object sorting.
arr.sort{$0.0["id"] > $0.1["id"] }
if it was a simple array, you can use the built it sort func: arr.sort(by: >) apple.co/2FqkBLl
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"]!) }

Comments

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.

Comments

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]});
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.