Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort by two properties

Tags:

ios

swift

swift3

my object looks like :

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

i want to sort it to have a result like :

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

So i need to sort by section, and in each section by order.

That's what i'm doing :

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

The string "section.." is just for the example, it can be other thing so i can't just use the character to sort. I need a real priority on X string.

like image 308
Makaille Avatar asked Dec 19 '16 14:12

Makaille


People also ask

How do you sort an array by two conditions?

The sort() callback function usually receives two arguments, say a and b, which are nothing but two elements of the array on which sort() was called and the callback function runs for each possible pair of elements of the array.


2 Answers

To sort it by two factors you can do your custom logic with the "sorted" method : Here is an example that you can test in 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's 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)
like image 126
LastMove Avatar answered Sep 30 '22 06:09

LastMove


Using Protocol

struct A {
    var firstName: String?
    var lastName: String?
}
protocol StringSortable {
    var property1: String {get}
    var property2: String {get}
}
extension A: StringSortable {
    var property1: String {
        return firstName ?? ""
    }
    var property2: String {
        return lastName ?? ""
    }
}
let array1 = [A(firstName: "Dan", lastName: "P2"), A(firstName: "Han", lastName: "P1"), A(firstName: "Dan", lastName: "P0"), A(firstName: "Han", lastName: "P8")]
let sortArray = array1.sorted {
    $0.property1 == $1.property1 ? $0.property2 < $1.property2 : $0.property1 < $1.property1
}
print(sortArray)

Dan P0

Dan P2

Han P1

Han P8

like image 37
jpulikkottil Avatar answered Sep 30 '22 06:09

jpulikkottil