Sum values in array of hash if they have the same value

arrays, hash, ruby

Solution

This seems work

array.group_by { |item| [item[:loading], item[:avg]] }.values.flat_map { |items| items.first.merge(total: items.sum { |h| h[:total] }) }
=> [{:loading=>10, :avg=>15, :total=>25}, {:loading=>20, :avg=>20, :total=>120}, {:loading=>30, :avg=>25, :total=>55}, {:loading=>10, :avg=>20, :total=>46}]

Problem

I saw this piece of code in this post, because I'm trying to sum values in an array of hashes based on some criteria. Rails sum values in an array of hashes ``` array = [ {loading: 10, avg: 15, total: 25 }, {loading: 20, avg: 20, total: 40 }, {loading: 30, avg: 25, total: 55 } ] sum = Hash.new(0) array.each_with_object(sum) do |hash, sum| hash.each { |key, value| sum[key] += value } end # => {:loading=>60, :avg=>60, :total=>120} ``` What I'm trying to do and I don't know how, is to sum total key if loading and avg appear with the same values more than once in this array. For instance. ``` array = [ {loading: 10, avg: 15, total: 25 }, {loading: 20, avg: 20, total: 40 }, # See here {loading: 30, avg: 25, total: 55 }, {loading: 20, avg: 20, total: 80 }, # See here {loading: 10, avg: 20, total: 46 } ] ``` The result would be: ``` [ {loading: 10, avg: 15, total: 25 }, {loading: 20, avg: 20, total: 120 }, # Results in this {loading: 30, avg: 25, total: 55 }, {loading: 10, avg: 20, total: 46 } ] ``` I tried to modify this line ``` hash.each { |key, value| sum[key] += value } ``` Adding a conditional that checks if the value is repeated but I didn't succeed. Any help, ideas or anything will be welcome.

Original source

Related problems