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.
You can use the sort method on an array, hash, or another Enumerable object & you'll get the default sorting behavior (sort based on <=> operator) You can use sort with a block, and two block arguments, to define how one object is different than another (block should return 1, 0, or -1)
The Ruby sort method works by comparing elements of a collection using their <=> operator (more about that in a second), using the quicksort algorithm. You can also pass it an optional block if you want to do some custom sorting. The block receives two parameters for you to specify how they should be compared.
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.
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