Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting NSMutableArray depending on priority

I have a NSMutableArray of Dictionary.

dic1 = ["user":"Smith","points":12,"lastPoints":4,online:3MonthsAgo(NSDate)]
dic2 = ["user":"Mike","points":22,"lastPoints":3,online:2MonthsAgo(NSDate)]
dic3 = ["user":"Mark","points":22,"lastRank":5,online:now(NSDate)]
dic4 = ["user":"Jay","points":16,"lastPoints":2,online:2minutes(NSDate)]
dic5 = ["user":"Alex","points":13,"lastPoints":5,online:1hr(NSDate)]
dic6 = ["user":"Peter","points":22,"lastPoints":3,online:2days(NSDate)]

I want to rearrage this in 3 ways, First users with top points will show first So

Mike:22
Mark:22
Peter:22
Jay:16
Alex:13
Smith:12

now that i did using

let sort = NSSortDescriptor(key: "points", ascending: false)

the next thing I want to do this sort this users again depending on lastPoints example

Mark:22:5
Mike:22:3
Peter:22:3
Jay:16:2
Alex:13:5
Smith:12:4

and then sort Mike's and Peter's position in array depending on their last online date. Now when i try

 let sortAgain = NSSortDescriptor(key: "lastPoints", ascending: false) and then
let sortAgain2 = NSSortDescriptor(key: "online", ascending: false)

It deletes the sort of points that i did before and sorts everything again depending on lastPoints. I want it to sort them depending on points and then see if points are equal, sort those points data depending on lastPoints. And if lastPoints are equal sort these equal datas depeding on "Online" date.

like image 590
user528432 Avatar asked Jun 04 '26 21:06

user528432


1 Answers

Try this:

let result = arr.sort {
    let p0 = $0["points"] as! Int
    let p1 = $1["points"] as! Int

    let lp0 = $0["lastPoints"] as! Int
    let lp1 = $1["lastPoints"] as! Int

    let online0 = $0["online"] as! NSDate
    let online1 = $1["online"] as! NSDate

    if p0 != p1 {
        return p0 > p1
    } else if lp0 != lp1 {
        return lp0 > lp1
    } else {
        return online0.timeIntervalSince1970 > online1.timeIntervalSince1970
    }
}
like image 77
Code Different Avatar answered Jun 07 '26 14:06

Code Different



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!