簡體   English   中英

按數組和求和變量分組以查看最高值

[英]Group by array and sum variable to see what is the highest

采取以下數組:

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

什么是下一個步驟? 謝謝。

可能的解決方案:

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

您可以在group_by和map之后使用max_by:

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.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_produtototal的最高金額。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM