I have an array of hashes which contains an id
field and a weight
field. 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. 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. I need to have id = 11
before id = 12
in the array. I really appreciate some guidance on this. Thank you!