按二次值排序二维数组

时间:2022-04-24 12:13:55

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]]?

好的,比方说我有一个类似[[z,1],[d,3],[e,2]]的数组,我怎么能用每个组成数组的第二个元素对这个数组进行排序?这样我的数组看起来如下? [[z,1],[e,2],[d,3]]?

2 个解决方案

#1


34  

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:

或者正如用户@Phrogz指出的那样,如果内部数组每个都有两个元素:

arr.sort_by{|x,y|y} # => [[:z, 1], [:e, 2], [:d, 3]]
arr.sort_by(&:last) # => [[:z, 1], [:e, 2], [:d, 3]]

#2


1  

As user maerics answer it provides Ascending sorting.This answer is very useful for me thanks. For Descending sorting i use -

作为用户maerics回答它提供升序排序。这个答案非常有用,谢谢。对于降序排序我使用 -

arr = [[:z,1], [:d,3], [:e,2]]
arr.sort {|a,b| a[1] <=> b[1]}.reverse
#=> [[:d, 3], [:e, 2], [:z, 1]]

#1


34  

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:

或者正如用户@Phrogz指出的那样,如果内部数组每个都有两个元素:

arr.sort_by{|x,y|y} # => [[:z, 1], [:e, 2], [:d, 3]]
arr.sort_by(&:last) # => [[:z, 1], [:e, 2], [:d, 3]]

#2


1  

As user maerics answer it provides Ascending sorting.This answer is very useful for me thanks. For Descending sorting i use -

作为用户maerics回答它提供升序排序。这个答案非常有用,谢谢。对于降序排序我使用 -

arr = [[:z,1], [:d,3], [:e,2]]
arr.sort {|a,b| a[1] <=> b[1]}.reverse
#=> [[:d, 3], [:e, 2], [:z, 1]]