Sort Array of Objects With Some Conditions

Noshaid Ali

I have an array of Users objects:

Class Users {
    var firstName:String!
    var lastName:String!
    var status:Int!

    override init(fn: String, ln: String, s: Int) {
        self.firstName = fn
        self.lastName = ln
        self.status = s
    }
}

var users:[Users] = [Users]()
users.append(Users(fn:"a", ln:"b", s:1))
users.append(Users(fn:"c", ln:"d", s:3))
users.append(Users(fn:"e", ln:"f", s:2))
users.append(Users(fn:"g", ln:"h", s:1))
users.append(Users(fn:"i", ln:"j", s:1))
users.append(Users(fn:"k", ln:"l", s:2))

I know the method to sort this array on status like

users = users.sorted(by: {$0.status > $1.status})

But, how could I sort users array on status with 2 on top then 3 and in the last 1 i.e [2,2,3,1,1,1]

Bilal

Try this. This will sort based on the order array. If any status is missing will be moved to bottom of the array.

let order = [2,3,1]
users = users.sorted(by: { order.index(of: $0.status) ?? Int.max < order.index(of: $1.status) ?? Int.max })
// 2,2,3,1,1,1

Lets say if 3 is missing in order array

let order = [2,1]
users = users.sorted(by: { order.index(of: $0.status) ?? Int.max < order.index(of: $1.status) ?? Int.max })
// 2,2,1,1,1,3

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related