Alicia Weenum
Alicia Weenum

Reputation: 1

How do I sum and group values in Array of Hashes?

I have the following data structure:

a = [
  { "payer": "UNILEVER", "points": 200, "timestamp": "2020-10-31T11:00:00Z" },
  { "payer": "DANNON", "points": -200, "timestamp": "2020-10-31T15:00:00Z" },
  { "payer": "MILLER COORS", "points": 10000, "timestamp": "2020-11-01T14:00:00Z" },
  { "payer": "DANNON", "points": 300, "timestamp": "2020-10-31T10:00:00Z" }
]

I want to sum up all point by payer. How can I do so?

Upvotes: 0

Views: 85

Answers (4)

max
max

Reputation: 101891

a.group_by {|h| h[:payer] }
 .transform_values {|a| a.sum {|h| h[:points] } }

# => {"UNILEVER"=>200, "DANNON"=>100, "MILLER COORS"=>10000}

Upvotes: 2

demir
demir

Reputation: 4709

You can get result with single loop:

a.each_with_object(Hash.new { |h, k| h[k] = 0 }) { |o, r| r[o[:payer]] += o[:points] }
# => {"UNILEVER"=>200, "DANNON"=>100, "MILLER COORS"=>10000}

Upvotes: 0

Amit Patel
Amit Patel

Reputation: 15985

a.group_by { |element| element[:payer] }.each_with_object({}) { |(payer, records), result| result[payer] = records.inject(0) { |sum, record| sum + record[:points]  } }
=> {"UNILEVER"=>200, "DANNON"=>100, "MILLER COORS"=>10000}

Upvotes: 1

Rajagopalan
Rajagopalan

Reputation: 6064

Input

a = [{ "payer": "UNILEVER", "points": 200, "timestamp": "2020-10-31T11:00:00Z" },
     { "payer": "DANNON", "points": -200, "timestamp": "2020-10-31T15:00:00Z" },
     { "payer": "MILLER COORS", "points": 10000, "timestamp": "2020-11-01T14:00:00Z" },
     { "payer": "DANNON", "points": 300, "timestamp": "2020-10-31T10:00:00Z" }]

Code

result=a.group_by { |h| h[:payer] }.values.map do |arr|
  arr.reduce do |h1, h2|
    h1.merge(h2) do |k, f, s|
      k.eql?(:points) ? f + s : f
    end
  end
end
p result

Output

#=>[{:payer=>"UNILEVER", :points=>200, :timestamp=>"2020-10-31T11:00:00Z"}, {:payer=>"DANNON", :points=>100, :timestamp=>"2020-10-31T15:00:00Z"}, {:payer=>"MILLER COORS", :points=>10000, :timestamp=>"2020-11-01T14:00:00Z"}]

Upvotes: 0

Related Questions