Shpigford
Shpigford

Reputation: 25378

Remove all but one duplicate from array of hashes

I have an array of hashes like this:

[
  { :color => 'red', :animal => 'dog' },
  { :color => 'blue', :animal => 'cat' },
  { :color => 'yellow', :animal => 'frog' },
  { :color => 'red', :animal => 'cat' },
  { :color => 'red', :animal => 'mouse' }
]

What I want to do is remove all but one of the duplicates based on one of the keys.

So in this case, I want to remove all but one of the items where color is red. Doesn't matter which one.

Final output would be something like this:

[
  { :color => 'blue', :animal => 'cat' },
  { :color => 'yellow', :animal => 'frog' },
  { :color => 'red', :animal => 'mouse' }
]

Again, when removing the duplicates, the one to keep does not matter.

Upvotes: 0

Views: 52

Answers (2)

user944938
user944938

Reputation: 1020

Another way of achieving this would be

.uniq { |h| h[:color] }

=> [{:color=>"red", :animal=>"dog"}, {:color=>"blue", :animal=>"cat"}, {:color=>"yellow", :animal=>"frog"}]

As @Victor suggested this is for ruby 1.9.2+

Upvotes: 2

Victor Moroz
Victor Moroz

Reputation: 9225

.group_by { |x| x[:color] }.values.map(&:first)

.inject({}) { |xs, x| xs[x[:color]] = x; xs }.values

Upvotes: 2

Related Questions