采取以下数组:
array = [{"filial"=>"01", "tipo_produto"=>"MR", "total"=>"1492.03"},
{"filial"=>"01", "tipo_produto"=>"MR", "total"=>"1492.03"},
{"filial"=>"01", "tipo_produto"=>"PA", "total"=>"1492.03"},
{"filial"=>"01", "tipo_produto"=>"PA", "total"=>"1492.03"}]
我需要按“tipo_produto”进行分组,然后将每个组的“总数”相加,以查看总计总数最高的组。最后,我需要知道哪个组最高。以下是我到目前为止的情况:
array2 = array.group_by { |d| d["tipo_produto"] }
导致了以下对象:
array2 = {"MR"=>[{"filial"=>"01", "tipo_produto"=>"MR", "total"=>"1492.03"},
{"filial"=>"01", "tipo_produto"=>"MR", "total"=>"1492.03"}],
"PA"=>[{"filial"=>"01", "tipo_produto"=>"PA", "total"=>"1492.03"},
{"filial"=>"01", "tipo_produto"=>"PA", "total"=>"1492.03"}]}
接下来的步骤是什么?谢谢。
答案 0 :(得分:1)
可能的解决方案:
# your first step
grouped_values = array.group_by {|d| d["tipo_produto"]}
# aggregate by total:
grouped_values.each do |k, v|
grouped_values[k] = v.inject(0) {|r, i| r + i['total'].to_f }
end
=> {"MR"=>2984.06, "PA"=>2984.06}
# find the highest:
grouped_values.max_by {|_, v| v}
=> ["MR", 2984.06]
答案 1 :(得分:1)
您可以在group_by和map:
之后使用max_byarray = [{ 'filial' => '01', 'tipo_produto' => 'MR', 'total' => '1492.03' },
{ 'filial' => '01', 'tipo_produto' => 'MR', 'total' => '1492.03' },
{ 'filial' => '01', 'tipo_produto' => 'PA', 'total' => '1492.03' },
{ 'filial' => '01', 'tipo_produto' => 'PA', 'total' => '1492.05' }]
array2 = array.group_by { |d| d['tipo_produto'] }
types_and_totals = array2.map { |type, products|
[
type,
products.map { |product| product['total'].to_f }.inject(&:+)
]
}
p types_and_totals.max_by { |_, total| total }
#=> ["PA", 2984.08]
它只输出tipo_produto
和total
以获得最高金额。