Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Sort Array of Arrays by Child Element

Tags:

arrays

ruby

I have an "array of arrays" that has two values included at a time.

array = [[:tuesday, 0.25], [:monday, 1], [:thursday, 0.75]]

I'd like to use the number in the "child" array to sort the "parent" array in descending order. The result would look like:

array = [[:monday, 1], [:thursday, 0.75], [:tuesday, 0.25]]

I'm not too sure where to begin here.

like image 855
Brandon Avatar asked Dec 31 '25 05:12

Brandon


2 Answers

You can pass a block to the sort method like this:

array.sort { |a, b| b[1] <=> a[1] }
like image 83
Alexander Lazarov Avatar answered Jan 01 '26 22:01

Alexander Lazarov


I would be inclined to write

array.sort_by(&:last).reverse
like image 44
Cary Swoveland Avatar answered Jan 01 '26 22:01

Cary Swoveland



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!