I have an array of hashes (price_params['items']
) where each item has a key called quantity
what I'm trying to do is to clean every duplicate of each item but keeping the count of the times the item was found in the array in the unique one that I'm leaving (using the quantity
key to keep that value)
This is my code so far:
def clean_duplicated_offers
price_params['items'].each do |item|
max_count = price_params['items'].count(item)
next unless max_count > 1
price_params['items'].delete(item)
item['quantity'] = max_count
price_params['items'] << item
end
end
It works well, but it feels weird to delete every occurrence of the item in the array just to add it back to it.
Is there any better way to achieve this?
price_params['items']
(Attempt to) insert each into the empty array. Ifitem
does not exist there, insert it, otherwise add one to the existingitem['quantity']
. Setprice_params['items']
to this new array. \$\endgroup\$