Sort by two properties

my object looks like this:

object = [[section: "section1", order: "1"], [section: "section2", order: "1"], [section: "section1", order: "2"], [section: "section2", order: "2"]] 

I want to sort it to get a result like:

 [[section: "section1", order: "1"], [section: "section1", order: "2"], [section: "section2", order: "1"], [section: "section2", order: "2"]] 

Therefore, I need to sort in sections and in each section in order.

What am I doing:

  return Observable.from(realm .objects(Section.self).sorted(byProperty: "order", ascending: true) 

The string "section .." is for reference only, it may be different, so I can’t just use the character to sort. I need a real priority for line X.

+6
source share
2 answers

To sort it for two reasons, you can execute your own logic using the sort method: Here is an example that you can test on a playground.

  struct MyStruct { let section: String let order: String } let array = [MyStruct(section: "section1", order: "1"), MyStruct(section: "section2", order: "1"), MyStruct(section: "section1", order: "2"), MyStruct(section: "section2", order: "2")] let sortedArray = array.sorted { (struct1, struct2) -> Bool in if (struct1.section != struct2.section) { // if it not the same section sort by section return struct1.section < struct2.section } else { // if it the same section sort by order. return struct1.order < struct2.order } } print(sortedArray) 
+5
source
 let object = [["section": "section1", "order": "2"], ["section": "section2", "order": "2"], ["section": "section1", "order": "1"], ["section": "section2", "order": "1"], ["section": "section5", "order": "3"], ["section": "section6", "order": "1"], ["section": "section5", "order": "1"]] let Ordered = object.sorted{$0["order"]! < $1["order"]! } let OrderedObjects = Ordered.sorted{$0["section"]! < $1["section"]! } print(OrderedObjects) //[["section": "section1", "order": "1"], ["section": "section1", "order": "2"], ["section": "section2", "order": "1"], ["section": "section2", "order": "2"], ["section": "section5", "order": "1"], ["section": "section5", "order": "3"], ["section": "section6", "order": "1"]] 
0
source

Source: https://habr.com/ru/post/1013290/


All Articles