我有一個陣列
[
{
"week_year": "49-2021",
"total": 6.5
},
{
"week_year": "45-2021",
"total": 28.5
},
{
"week_year": "45-2021",
"total": 6.5
},
{
"week_year": "44-2021",
"total": 6.5
},
{
"week_year": "46-2021",
"total": 14.5
}
]
我想按相同的 week_year 對它進行分組,并總結每周的總數。還有其他方法可以做到這一點嗎?
uj5u.com熱心網友回復:
您可以將group_by與transform_values結合使用:
array.group_by { |a| a[:week_year] }
.transform_values { |values| values.sum { |value| value[:total] } }
哪個將回傳:
{
"49-2021" => 6.5,
"45-2021" => 35.0,
"44-2021" => 6.5,
"46-2021" => 14.5
}
uj5u.com熱心網友回復:
如果需要的輸出是這樣的,{ week_year => total }那么您可以使用group_by,transform_values和的組合sum:
arr
.group_by { |hash| hash[:week_year] }
.transform_values { |arr| arr.sum { |hash| hash[:total] } }
# {"49-2021"=>6.5, "45-2021"=>35.0, "44-2021"=>6.5, "46-2021"=>14.5}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/359684.html
上一篇:FlutterSlider–即使用戶關閉應用程式并使用Getx重新訪問也保持打開/關閉
下一篇:如何將資料放入表中?
