Sorting a two-dimensional array by second value

后端 未结 2 937
渐次进展
渐次进展 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 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]]
    

提交回复
热议问题