Sorting a two-dimensional array by second value

后端 未结 2 897
渐次进展
渐次进展 2021-01-31 18:17

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?

相关标签:
2条回答
  • 2021-01-31 18:58
    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]]
    
    0 讨论(0)
  • 2021-01-31 19:06

    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]]
    
    0 讨论(0)
提交回复
热议问题