Charles Charles - 7 months ago 10
Ruby Question

How to get rid of the duplicate and also with the large value?

My list contains

User1, 0


User2, 50


User3, 30


User1, 50


User3, 68


How do I get rid of the duplicates, but take the largest value out of them?

Like need to contain this:
User1, 50
,
User2, 50
,
User3, 68
and get rid of
User1, 0
and
User3, 30

Answer

There are many ways to do that. Here's are three.

arr = [[:User1, 0], [:User2, 50], [:User3, 30], [:User1, 50], [:User3, 68]]

#1 Use Hash#update (aka Hash#merge!)

arr.each_with_object({}) { |(u,x),h| h.update(u=>x) { |_,o,n| [o,n].max } }.to_a
  #=> [[:User1, 50], [:User2, 50], [:User3, 68]]

#2 Order the elements by the second value (using Enumerable#sort_by) and convert to a hash

arr.sort_by(&:last).to_h
  #=> {:User1=>50, :User3=>68, :User2=>50} 

#3 Use Enumerable#group_by

arr.group_by(&:first).map { |k,v| [k, v.map(&:last).max] }
  #=> [[:User1, 50], [:User2, 50], [:User3, 68]]