Remove duplicate from array in ruby

I want to output an array of hashes with name, which will be unique to all hashes. How will I do this with ruby?

This is my input:

input = [{:name => "Kutty", :score => 2, :some_key => 'value', ...},
         {:name => "Kutty", :score => 4, :some_key => 'value', ...},
         {:name => "Baba", :score => 5, :some_key => 'value', ...}]

I want the result to look like this:

  output = [{:name => "Kutty", :score => 4, :some_key => 'value', ...},
            {:name => "Baba", :score => 5, :some_key => 'value', ...}]
+5
source share
4 answers

To simply remove duplicates based on: name, just try;

output = input.uniq { |x| x[:name] }

Demo is here .

Change: . Since you added the sorting requirement to the comments, here's how to select the highest score entry for each name, if you use Rails, I see that you already have the answer for the "standard" Ruby above;

output = input.group_by { |x| x[:name] }
              .map {|x,y|y.max_by {|x|x[:score]}}

; groups , . , maps .

.

+15
input = [{:name => "Kutty", :score => 2, :some_key => 'value'},{:name => "Kutty", :score => 4, :some_key => 'value'},{:name => "Baba", :score => 5, :some_key => 'value'}]
p input.uniq { |e| e[:name] }

ruby > 1.9, ruby ​​ - :

input = [{:name => "Kutty", :score => 2, :some_key => 'value'},{:name => "Kutty", :score => 4, :some_key => 'value'},{:name => "Baba", :score => 5, :some_key => 'value'}]
unames = []
new_input = input.delete_if { |e|
  if unames.include?(e[:name])
    true
  else
    unames << e[:name]
    false
  end
}
p new_input
+3

Try this solution.

input = [{:name => "Kutty", :score => 2, :some_key => 'value'},
         {:name => "Kutty", :score => 4, :some_key => 'value'},
         {:name => "Baba", :score => 5, :some_key => 'value'}]


a = []
output = []
input.collect do |i|
  input.delete(i) if !a.include?(i[:name])
  output << i if !a.include?(i[:name])
  a << i[:name] if !a.include?(i[:name])
end


output = [{:some_key=>"value", :name=>"Kutty", :score=>2}, 
          {:some_key=>"value", :name=>"Baba", :score=>5}] 

UPDATED

output = {}
input.each do |e|
  ref = output[e[:name]]
  if ref && ref[:score] > e[:score]
    #nothing
  else
    output[e[:name]] = e
  end
end

check output:

puts output.values
+3
source
input.uniq{|hash| hash[:name]}
+1
source

All Articles