Wayne Rumble Wayne Rumble - 4 months ago 13
Ruby Question

Count duplicate hashes in an array, ruby

I have an array of hashes like the following:

basket = [
{code: "001", name: "Lavender Heart", price: 8.50},
{code: "001", name: "Lavender Heart", price: 8.50},
{code: "002", name: "Shoes", price: 18.50},
{code: "002", name: "Shoes", price: 18.50},
{code: "003", name: "Chocolate", price: 4.50}
]


and want to take any duplicates and put them into an array so that the count is the key and the duplicate hash is the value.

so for the above i would end up with:

[2 => {code: "001", name: "Lavender Heart", price: 8.50},
2 => {code: "002", name: "Shoes", price: 18.50}]


How can I do this?

Answer

You can use group_by to find the number of duplicates, and then display the results using map:

basket.group_by { |x| x }.map { |k, v| {v.count => k} }
# => [{2=>{:code=>"001", :name=>"Lavender Heart", :price=>8.5}}, 
#     {2=>{:code=>"002", :name=>"Shoes", :price=>18.5}}, 
#     {1=>{:code=>"003", :name=>"Chocolate", :price=>4.5}}]