Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting a multidimensional array in ruby

Tags:

ruby

I have the following array:

[["2010-01-10", 2], ["2010-01-09", 5], ["2009-12-11", 3], ["2009-12-12", 12], ["2009-12-13", 0]]

I just want to sort it by the second value in each group and return the highest one, like i want to the output to be 12 with the given input above.

update

I might add that I made this into an array using to_a, from a hash, so if there is away to do the same with a hash that would be even better.

like image 203
JP Silvashy Avatar asked Jan 12 '10 03:01

JP Silvashy


3 Answers

To sort by second value

x=[["2010-01-10", 2], ["2010-01-09", 5], ["2009-12-11", 3], ["2009-12-12", 12], ["2009-12-13", 0]]

x.sort_by{|k|k[1]}
=> [["2009-12-13", 0], ["2010-01-10", 2], ["2009-12-11", 3], ["2010-01-09", 5], ["2009-12-12", 12]]
like image 167
YOU Avatar answered Nov 11 '22 10:11

YOU


Call the sort method on your hash to sort it.

hash = hash.sort { |a, b| b[1] <=> a[1] }

Then convert your hash to an array and extract the first value.

result = hash.to_a[0][1]
like image 8
Frank Mitchell Avatar answered Nov 11 '22 08:11

Frank Mitchell


Use this on your hash:

hash.values.max

If you only need the highest element, there is no need to sort it!

like image 7
Chris Jester-Young Avatar answered Nov 11 '22 08:11

Chris Jester-Young