Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return min values of hash with duplicate values

Tags:

ruby

For example, if I have the hash {"a" => 1, "b" => 2, "c" => 1}, I want ["a", "c"].

I can do hash.min_by{|k,v| v}, but that only returns the first match ("a"=>1).

How do I get it to recognize duplicates and return {"a"=> 1, "c"=> 1}?

like image 384
Chris Avatar asked Nov 25 '25 12:11

Chris


2 Answers

That operation is a bit unusual for a hash, so it’s not very neat:

min_value = hash.values.min
min_pairs = hash.select { |k, v| v == min_value }
like image 74
Ry- Avatar answered Nov 28 '25 02:11

Ry-


{"a" => 1, "b" => 2, "c" => 1}.group_by(&:last).min.last.map(&:first)
# => ["a", "c"]

or

{"a" => 1, "b" => 2, "c" => 1}.group_by(&:last).min.last.to_h.keys
# => ["a", "c"]
like image 44
sawa Avatar answered Nov 28 '25 03:11

sawa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!