user6107657 user6107657 - 1 year ago 81
Ruby Question

Delete Duplicates in Multi-Dimension Array


I want to
the array by first element, but keep the item that has the largest second element

result should be


Here is my code:

A.uniq{|i| i.first}
=> [[a,1],[b,1]]

Answer Source

You could use Enumerable#group_by and Enumerable#max_by.


A.group_by(&:first).map { |_,v| v.max_by(&:last) }
  #=> [["a", 3], ["b", 3]] 

The two steps:

h = A.group_by(&:first)
  #=> {"a"=>[["a", 3], ["a", 2], ["a", 1]], "b"=>[["b", 1], ["b", 3]]} { |_,v| v.max_by(&:last) }
  #=> [["a", 3], ["b", 3]] 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download