Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the unique elements of an array with a maximum value of attribute

Tags:

arrays

ruby

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}]
like image 266
kuatro Avatar asked Jan 16 '26 18:01

kuatro


2 Answers

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}]
like image 161
Sergio Tulentsev Avatar answered Jan 19 '26 08:01

Sergio Tulentsev


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}]
like image 27
Arup Rakshit Avatar answered Jan 19 '26 07:01

Arup Rakshit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!