简体   繁体   English

如何对具有多个值的哈希数组进行排序?

[英]How to sort an array of hashes with multiple values?

I have an array of hashes which contains an id field and a weight field.我有一个哈希数组,其中包含一个id字段和一个weight字段。 I am able to sort it based on weight but I also need to make sure that the id field is sorted if there are duplicate weights.我可以根据weight对其进行排序,但我还需要确保如果存在重复权重,则对id字段进行排序。 Below is the code snippet for reference.下面是代码片段供参考。

# Input
arr = [{"id" => 10, "weight" => 23}, {"id" => 6, "weight" => 43}, {"id" => 12, "weight" => 5}, {"id" => 15, "weight" => 30}, {"id" => 11, "weight" => 5}]

arr.sort_by{|k| k["weight"]}

# Output: [{"id"=>12, "weight"=>5}, {"id"=>11, "weight"=>5}, {"id"=>10, "weight"=>23}, {"id"=>15, "weight"=>30}, {"id"=>6, "weight"=>43}]

# Expected output = [{"id"=>11, "weight"=>5}, {"id"=>12, "weight"=>5}, {"id"=>10, "weight"=>23}, {"id"=>15, "weight"=>30}, {"id"=>6, "weight"=>43}]

In the above example, id = 12 and id = 11 have the duplicate values.在上面的示例中, id = 12id = 11具有重复值。 I need to have id = 11 before id = 12 in the array.我需要在数组中的id = 12之前有id = 11 I really appreciate some guidance on this.我真的很感谢这方面的一些指导。 Thank you!谢谢!

You can use Enumerable#sort_by with an array too.您也可以将Enumerable#sort_by与数组一起使用。 Note the order of the values in the array.请注意数组中值的顺序。

arr.sort_by {|k| k.values_at("weight", "id") }

Quote from the docs of Array#<=> about how comparison of array works:引用Array#<=>文档中关于Array#<=>比较如何工作的内容:

Arrays are compared in an “element-wise” manner;数组以“元素方式”的方式进行比较; the first element of ary is compared with the first one of other_ary using the <=> operator, then each of the second elements, etc… As soon as the result of any such comparison is non zero (ie the two corresponding elements are not equal), that result is returned for the whole array comparison.使用<=>运算符将ary的第一个元素与other_ary的第一个元素进行比较,然后是每个第二个元素,等等……只要任何此类比较的结果非零(即两个对应元素不相等) ),则返回整个数组比较的结果。

You can use Array#sort with the spaceship operator like so:您可以将Array#sortspaceship 运算符一起使用,如下所示:

arr.sort do |a,b|
  if a["weight"] == b["weight"]
    a["id"] <=> b["id"]
  else
    a["weight"] <=> b["weight"]
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM