Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an Array of objects given an ordered list of ids

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 !!!

like image 623
dgilperez Avatar asked Oct 17 '11 00:10

dgilperez


People also ask

How do you sort an array of objects based on ID?

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 ?

How do you sort data in an ordered array?

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.

How do you sort an array of objects based on another array?

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.

How do you sort an array of objects based on a property?

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.


1 Answers

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] }
like image 121
peakxu Avatar answered Oct 20 '22 22:10

peakxu