Sorting a two-dimensional array by second value

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

提交回复
热议问题