Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby/rails sort an array of records based on an array of string

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.

like image 598
user3344199 Avatar asked Feb 13 '23 09:02

user3344199


1 Answers

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 == to obj. Returns nil 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.

like image 181
Arup Rakshit Avatar answered Feb 14 '23 23:02

Arup Rakshit