user6107657 user6107657 - 6 months ago 6
Ruby Question

Delete Duplicates in Multi-Dimension Array

A=[[a,3],[a,2],[a,1],[b,1],[b,3]]


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

result should be

[[a,3],[b,3]]


Here is my code:

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

Answer

You could use Enumerable#group_by and Enumerable#max_by.

A=[['a',3],['a',2],['a',1],['b',1],['b',3]]

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]]} 
h.map { |_,v| v.max_by(&:last) }
  #=> [["a", 3], ["b", 3]] 
Comments