user7754069 -4 years ago 130
Ruby Question

Group array of hashes by multiple keys to find average in Ruby

I have found solution for my problem done in JS but i need it done in Ruby (RoR). Here is link to problem and solution: Find average value for array of hashes using multiple group by

So i have array of hashes that needs to be grouped by keys (first

`subject_id`
then
`element_id`
) and then find average values for them. Number of hashes in array is not fixed.

Below is input array:

``````a=[
{:subject_id=>1, :element_id=>2, :value=>55},
{:subject_id=>1, :element_id=>4, :value=>33},
{:subject_id=>1, :element_id=>2, :value=>33},
{:subject_id=>1, :element_id=>4, :value=>1},
{:subject_id=>1, :element_id=>2, :value=>7},
{:subject_id=>1, :element_id=>4, :value=>4},
{:subject_id=>2, :element_id=>2, :value=>3},
{:subject_id=>2, :element_id=>2, :value=>5},
{:subject_id=>2, :element_id=>4, :value=>9}
]
``````

Result:

``````b=[
{:subject_id=>1, :element_id=>2, :value=>95},
{:subject_id=>1, :element_id=>4, :value=>38},
{:subject_id=>2, :element_id=>2, :value=>8},
{:subject_id=>2, :element_id=>4, :value=>9}
]
``````

Answer Source

The result shown in the question isn't the average, it's the sum, so the result will be different:

``````  def groupByAndAverage(a)
b = []

a.each_with_index do |element, key|
index = b.index do |x|
x != element &&
x[:subject_id] == element[:subject_id] &&
x[:element_id] == element[:element_id]
end
if index
b[index][:value] += element[:value]
b[index][:amount] += 1
else
b.push a[key].merge(amount: 1)
end

true
end
b.map do |element|
element[:value] = element[:value] / element[:amount]
element.delete(:amount)
element
end
b
end
``````

And the result from this is:

``````  [{:subject_id=>1, :element_id=>2, :value=>31},
{:subject_id=>1, :element_id=>4, :value=>12},
{:subject_id=>2, :element_id=>2, :value=>4},
{:subject_id=>2, :element_id=>4, :value=>9}]
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download
Latest added