Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a mixed array by different elements in Ruby?

I have an array similar to this:

a = [
  [0, {:a=>"31", :b=>"21"}],
  [1, {:a=>"32", :b=>"11"}],
  [1, {:a=>"25", :b=>"19"}],
  [0, {:a=>"12", :b=>"10"}]
]

And I want to sort it by the first element of each row or by the various elements of the hash (2nd element in the row).

like image 341
shabdar Avatar asked Aug 16 '26 02:08

shabdar


1 Answers

to sort by the first item in the Array:

> a.sort_by{|x| x.first}
 => [[0, {:a=>"31", :b=>"21"}], 
     [0, {:a=>"12", :b=>"10"}], 
     [1, {:a=>"32", :b=>"11"}], 
     [1, {:a=>"25", :b=>"19"}]] 

to sort by the first item in the Hash:

> a.sort_by{|x| x.last.first}
 => [[0, {:a=>"12", :b=>"10"}],
     [1, {:a=>"25", :b=>"19"}], 
     [0, {:a=>"31", :b=>"21"}], 
     [1, {:a=>"32", :b=>"11"}]] 

or you could sort by a given key of the hash:

> sort_key = :b
> a.sort_by{|x| x.last[ sort_key ]}
 => [[0, {:a=>"12", :b=>"10"}],
     [1, {:a=>"32", :b=>"11"}],
     [1, {:a=>"25", :b=>"19"}],
     [0, {:a=>"31", :b=>"21"}]] 

If you want to sort by the first array value, and then by the first entry in the hash, as a secondary search criteria, the answer is:

> a.sort_by{|x| [x.first, x.last.first]}
 => [[0, {:a=>"12", :b=>"10"}], 
     [0, {:a=>"31", :b=>"21"}], 
     [1, {:a=>"25", :b=>"19"}], 
     [1, {:a=>"32", :b=>"11"}]] 
like image 114
Tilo Avatar answered Aug 18 '26 17:08

Tilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!