Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort array based on key?

I have an array which has two types of objects: Awarded and non-awarded. I simply want to sort my array so that awarded objects are placed first, and the rest are placed afterwards.

Here is the code that defines the key "awarded":

if let awarded = achievements[indexPath.row].userRelation["awarded"] as? String where awarded != "<null>" { }

Within those brackets I'd like to use my unwrapped value "awarded" to sort through the achievements and add those to the beginning, and the rest at the end.

How would I go about doing that?

like image 686
Faisal Syed Avatar asked Dec 06 '25 16:12

Faisal Syed


1 Answers

You should experiment with sort function, it is very useful.

let sortedAchievements = achievements.sorted{ $0.userRelation["awarded"] < $1.userRelation["awarded"] }

To sort in place use this:

achievements.sort{ $0.userRelation["awarded"] < $1.userRelation["awarded"] }

I would recommend to refactor your model. It's better to use objects or structs instead of dictionaries. Also awarded should be a Bool property, not a String, right?

like image 180
alexburtnik Avatar answered Dec 08 '25 08:12

alexburtnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!