Ok, say I have an array like so [[z,1], [d,3], [e,2]], how can I sort this array by the second element of each constituent array? So that my array would look like the following? [[z,1], [e,2], [d,3]]?
-
2Note that this is really an array of arrays, not a 2-dimensional array.Phrogz– Phrogz2011-08-11 23:25:45 +00:00Commented Aug 11, 2011 at 23:25
-
possible duplicate of Sort a collection of objects by number (highest first) then by letter (alphabetical)Andrew Grimm– Andrew Grimm2011-08-11 23:32:39 +00:00Commented Aug 11, 2011 at 23:32
Add a comment
|
2 Answers
arr = [[:z,1], [:d,3], [:e,2]]
arr.sort {|a,b| a[1] <=> b[1]}
# => [[:z, 1], [:e, 2], [:d, 3]]
Or as user @Phrogz points out, if the inner arrays have exactly two elements each:
arr.sort_by{|x,y|y} # => [[:z, 1], [:e, 2], [:d, 3]]
arr.sort_by(&:last) # => [[:z, 1], [:e, 2], [:d, 3]]
4 Comments
Phrogz
Or more simply:
arr.sort_by{|s,n| n } or even arr.sort_by(&:last) (in Ruby 1.9).noraj
@Phrogz Prefer
sort because in ruby 2.4 (since 2.0 in fact or even before) sort_by doesn't exist but only sort_by! and the doc says that: The result is not guaranteed as stable. When two keys are equal, the order of the corresponding elements is unpredictable. So in order to use sort_by! you must have uniq keys. So @maerics please edit your post to say that or remove sort_by.maerics
@noraj note that arrays are
Enumerable#sort_by since at least v1.8.7 and stability was not requested in the question.kraftydevil
what about sorting by second column and then any ties would be sorted by the first column?
As user maerics answer it provides Ascending sorting.This answer is very useful for me thanks. For Descending sorting i use -
arr = [[:z,1], [:d,3], [:e,2]]
arr.sort {|a,b| a[1] <=> b[1]}.reverse
#=> [[:d, 3], [:e, 2], [:z, 1]]