I have an array of user records, and I would like to sort the users based on priority, which is stored in an array of strings and this array is always changing.
so if i have users =
User id: 1, username: "so_admin", priority: "Monday"
User id: 2, username: "so_staff", priority: "Wednesday"
priority = ["Wednesday","Tuesday","Friday"]
How can I sort my users so that users where their priority is "Wednesday" are listed first, etc.
You can do as
users.sort_by { |u| priority.index(u.priority) || priority.size }
The above sorting is done, with the assumption that the below Array
will be sorted as per your need, will hold all uniq values. users
array then will use the index of the sorted array.
priority = ["Wednesday","Tuesday","Friday"]
index(obj) → int or nil
Returns the index of the first object in
ary
such that the object is==
toobj
. Returnsnil
if no match is found.
priority
array doesn't hold all weekdays, rather 3
. I thought, if any users has priority, which is not present in the priority
array, let those users be placed in the last array. Suppose, for any user there is a priority, "Sunday"
, then, that user will be given lowest priority. How ?
Look at the expression priority.index(u.priority) || priority.size
, now with above mentioned sample, priority.index("sunday")
gives nil
, and right hand side expression of the ||
will be evaluated, i.e. priority.size
, which 3
. That's how that user
will be moved to the tail of the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With