Home > Back-end >  How to group json array and sum its total per week?
How to group json array and sum its total per week?

Time:11-18

I have an array

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

I want to group it by the same week_year and sum its total per week. Any other way to do that?

CodePudding user response:

You can use group_by in combination with transform_values:

array.group_by { |a| a[:week_year] }
     .transform_values { |values| values.sum { |value| value[:total] } }

Which will return:

{
 "49-2021" => 6.5,
 "45-2021" => 35.0,
 "44-2021" => 6.5,
 "46-2021" => 14.5
}

CodePudding user response:

If the output needed is like { week_year => total } then you can use a combination of group_by, transform_values and 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}
  • Related