I want to find out the largest sub array out of a multidimensional array in ruby. I have a multidimensional array as follows :
array = [[1,20],[2,40],[5,100],[7,15],[9,22]]
I want the first element of the sub array which second element is largest like in the above example I want the 5
as an output because second element of sub array [5,100]
is largest which is 100
. The output would be 5
.
And if more then one element are maximum than i want all these.
Ex: array = [[1,20],[2,40],[5,100],[7,15],[9,22],[12,100]]
The out put in this case would be [5,12]
Thanks in advance.
You can use the Enumerable#max_by
method to select the max element, and then project that element to the result value.
array.max_by{|a| a[1]}[0]
UPDATE:
If you want all the elements with the maximum value, you can first get the max value from the array, and then filter the array with that value.
max_value = array.max_by{|a| a[1]}[1]
results = array.select{|a| a[1] == max_value}.map(&:first)
You may use one line expression, but I think that's less readable
array.group_by{|a| a[1]}.max_by{|k,v| k}[1].map(&:first)
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