I have an array of objects:
[{id:1, price:10},{id:2, price:9},{id:3, price:8},{id:1, price:7}]
Now, how to get the array with unique id's, but in case of choosing between two objects with the same id's get the maximum value ({id:1, price:10})?
Expected result:
[{:id=>1, :price=>10}, {:id=>2, :price=>9}, {:id=>3, :price=>8}]
Something like this, maybe?
a = [
{id:1, price:10},
{id:2, price:9},
{id:3, price:8},
{id:1, price:7}
]
b = a.group_by{|h| h[:id]}.
map{|_, v| v.max_by {|el| el[:price]}}
b # => [{:id=>1, :price=>10}, {:id=>2, :price=>9}, {:id=>3, :price=>8}]
I'd do using Enumerable#sort_by and Array#uniq
a = [{id:1, price:10},{id:2, price:9},{id:3, price:8},{id:1, price:7}]
a.sort_by { |h| -h[:price] }.uniq { |h| h[:id] }
# => [{:id=>1, :price=>10}, {:id=>2, :price=>9}, {:id=>3, :price=>8}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With