13

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.

starblue
  • 55,348
  • 14
  • 97
  • 151
ere
  • 1,739
  • 3
  • 19
  • 41

4 Answers4

34

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.

Edu
  • 1,949
  • 1
  • 16
  • 18
2

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]] 
nolith
  • 613
  • 6
  • 16
  • 5
    You should *always* use `sort_by` for a keyed sort. Not only is it *much easier* to read, it is also more efficient. In this case it would be `a.sort_by {|el| el[1] }`, which, in this case, is the same as `a.sort_by(&:last)`. – Jörg W Mittag Mar 08 '12 at 12:52
  • 1
    How can we use this a.sort_by { |el| el[1] } if we want to order it descending? – Vini.g.fer Jun 10 '15 at 15:30
  • @Vini.g.fer a.sort_by { |el| el[1] * -1} if el[1] is number – Abel Jan 31 '18 at 18:04
1

Using the Array#sort method:

ary = [["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]
ary.sort { |a, b| b[1] <=> a[1] }
1

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]}
Waynn Lue
  • 11,344
  • 8
  • 51
  • 76