Kyle H
Kyle H

Reputation: 3295

How to sort array of objects using values from a second array

I have an array of objects and I need to sort them by the values of an attribute. The order to sort is given in the second array.

a = [ object1, object2, object3, object4]

object1.job = 'ER'
object2.job = 'AD'
object3.job = 'WE'
object4.job = 'ER'

b = ['ER', 'ER', 'WE', 'AD']

I need to sort my array a so that it returns [object1/object4, object3, object2]. How can I use my array b as a key for the sorting?

Upvotes: 1

Views: 57

Answers (1)

Mark Reed
Mark Reed

Reputation: 95242

This should work:

sorted_a = a.sort_by { |obj| b.index obj.job }

Note that b doesn't need to have multiple copies of ER; it just needs to indicate that ER comes before WE and AD.

b = ['ER', 'WE', 'AD']

The index function returns the position of its argument in its invocant:

b.index 'ER'  #=> 0
b.index 'AD'  #=> 2

And the sort_by method runs the supplied block on each element of the array and uses the results as the keys to sort by.

Upvotes: 4

Related Questions