简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM