如何获取具有最大属性值的数组的唯一元素

时间:2014-01-24 11:48:40

标签: ruby arrays

我有一个对象数组:

[{id:1, price:10},{id:2, price:9},{id:3, price:8},{id:1, price:7}]

现在,如何获取具有唯一ID的数组,但是如果在具有相同id的两个对象之间进行选择,则获得最大值({id:1, price:10})?

预期结果:

[{:id=>1, :price=>10}, {:id=>2, :price=>9}, {:id=>3, :price=>8}]

2 个答案:

答案 0 :(得分:3)

这样的事,也许?

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}]

答案 1 :(得分:3)

我会使用Enumerable#sort_byArray#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}]