I have a collection of objects @users
, each having its id
attribute.
@users = [#<User id:1>, #<User id:2>]
I also have an ordered Array of ids
.
ids = [2,1]
¿Is there a magical way to sort the collection using that list of ids? Without making another call to the database, if possible.
Thank you !!!
IF you mean that you wanted them sorted by id and if the id matches, you want them sorted by name then use this: items. sort(function(a, b) { if (a.id !== b.id) { return a.id - b.id } if (a.name === b.name) { return 0; } return a.name > b.name ?
The elements of an array can be arranged in order by using a static sort() method of the Arrays class. There are sort() methods for arrays of type byte[], char[], double[], float[], int[], and long[] . There is also a method that can sort object references based on the values of the objects.
If you use the native array sort function, you can pass in a custom comparator to be used when sorting the array. The comparator should return a negative number if the first value is less than the second, zero if they're equal, and a positive number if the first value is greater.
Example 1: Sort Array by Property NameThe sort() method sorts its elements according to the values returned by a custom sort function ( compareName in this case). Here, The property names are changed to uppercase using the toUpperCase() method. If comparing two names results in 1, then their order is changed.
Try this. First, build up a reverse mapping from id -> user.
ids_users = {}
@users.each {|user| ids_users[user.id] = user}
Then, use the ids order
ids.collect{ |id| ids_users[id] }
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