Reputation: 1779
I'm having a problem figuring out how I can sort an array of an array. Both arrays are straight forward and I'm sure it's quite simple, but I can't seem to figure it out.
Here's the array:
[["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]
I want to sort it by the integer value of the inner array which is a value of how many times the word has occurred, biggest number first.
Upvotes: 13
Views: 11314
Reputation: 613
sort can be used with a block.
a = [["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]
a.sort { |o1, o2| o1[1] <=> o2[1] }
#=> [["happy", 1], ["mad", 1], ["sad", 2], ["bad", 3], ["glad", 12]]
Upvotes: 2
Reputation: 11375
This should do what you want.
a = [["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]
a.sort {|x,y| y[1] <=> x[1]}
Upvotes: 1
Reputation: 598
Using the Array#sort method:
ary = [["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]
ary.sort { |a, b| b[1] <=> a[1] }
Upvotes: 1
Reputation: 1969
Try either:
array = [["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]
sorted = array.sort {|a,b| a[1] <=> b[1]}
Or:
array = [["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]
sorted = array.sort {|a,b| b[1] <=> a[1]}
Depending if you want ascending or descending.
Upvotes: 34