简体   繁体   中英

How to access and map a Hash to minimum value when there are multiple values per key?

I'm looking to map an ID to the latest year.

If I have a hash which has one key to one value I don't have a problem:

hash = { 
  "123456"=>[["123456", "1975"], ["123456", "2009"]],
  "123999"=>[["123999", "1928"], ["123999", "2012"]] 
}

hash.map{|key, value| value.max}

# => [["123456", "2009"], ["123999", "2012"]]

I'm hoping to do the same but with the "value" having another element:

Existing

new_hash = { 
  "123456"=>[["123456", "1975", "ST"], ["123456", "2009", "PE"]],
  "123999"=>[["123999", "1928", "ST"], ["123999", "2012", "PE"]] 
}

Essentially again, what I'm looking to retrieve is the entry with the latest year, while keeping the third element, as below:

Desired

# => [["123456", "2009", "PE"], ["123999", "2012", "PE"]]

How would I go about doing this?

TryEnumerable#max_by :

new_hash = { 
  "123456"=>[["123456", "1975", "ST"], ["123456", "2009", "PE"]],
  "123999"=>[["123999", "1928", "ST"], ["123999", "2012", "PE"]] 
}

new_hash.map { |_, array| array.max_by { |_, year,_| year } }

#=> [["123456", "2009", "PE"], ["123999", "2012", "PE"]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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