Home > OS >  Efficient way to find average of values in an array of hashes grouping by another value
Efficient way to find average of values in an array of hashes grouping by another value

Time:08-30

I'm collecting some data using some API calls. Now I have this data

data = [
  {:energyCons=>0.64, :energyCons100=>64, :energyClass=>"B"},
  {:energyCons=>0.64, :energyCons100=>64, :energyClass=>"B"},
  {:energyCons=>0.64, :energyCons100=>64, :energyClass=>"B"},
  {:energyCons=>0.64, :energyCons100=>64, :energyClass=>"B"},
  {:energyCons=>0.64, :energyCons100=>64, :energyClass=>"B"}
]

I need to group by energyClass and then get the average for energyCons and energyCons100

Basically, I need a simple array with

["B": {energyCons: 0.74, energyCons100: 82}, "C": {energyCons: 0.74, energyCons100: 82}.... ]

where the key is the energy class I group and the value is a hash with the two averages.

I can do that but only with multiple loops, is there any compact way?

CodePudding user response:

You could first group data by every element's energyClass value and then do the proper calculation;

data
  .group_by { |d| d[:energyClass] }
  .transform_values do |values|
    {
      energyCons: values.sum { |v| v[:energyCons] } / values.size,
      energyCons100: values.sum { |v| v[:energyCons100] } / values.size
    }
  end
  •  Tags:  
  • ruby
  • Related