I have an array that looks like the following:
[
{ type: 'A', price: '0.01' },
{ type: 'B', price: '4.23' },
{ type: 'D', price: '2.29' },
{ type: 'B', price: '3.38' },
{ type: 'C', price: '1.15' }
]
I need to group these by type
and then sort them by ascending price
. I can half solve this problem by doing the following:
boards.sort_by {|e| [e['type'], e['price'].to_f]}
Unfortunately, this sorts the type
s alphabetically when they should be sorted BADC
How do I sort the array by the pre-determined rules?
ar=[
{ type: 'A', price: '0.01' },
{ type: 'B', price: '4.23' },
{ type: 'D', price: '2.29' },
{ type: 'B', price: '3.38' },
{ type: 'C', price: '1.15' }
]
SORT_ORDER = 'BADC' #could also be an array, eg ["monday", "tuesday", ...]
p ar.sort_by{|e| [SORT_ORDER.index(e[:type]), e[:price].to_f]}
Output:
[{:type=>"B", :price=>"3.38"},
{:type=>"B", :price=>"4.23"},
{:type=>"A", :price=>"0.01"},
{:type=>"D", :price=>"2.29"},
{:type=>"C", :price=>"1.15"}]
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