简体   繁体   中英

If I have a collection of hashes with the same key and values, how do I add another value together?

I've assigned these rows to hashes:

other_id: 1,amount: 9290,id: 1
other_id: 2,amount: 2262,id: 1
other_id: 3,amount: 9588,id: 2
other_id: 4,amount: 1634,id: 2

How do I add together the amount values for a specific id , so for id: 1 , I need the total = 9290 + 2262 ?

Even better, if I had a large collection of these, how would I write code so that it would find the id number with the maximum value of total if total is the sum of all amount instances for a specific id number?

Assuming your input looks like this:

array = [{id: 1, amount: 9290, other_id: 123}, {id: 1, amount: 1234, other_id: 30}, {id: 2, amount: 4444, other_id: 456}]

Q1

specific_id = 1 # or whatever you are looking for
sum = array.inject(0) do |sum, hash|
  sum += hash[:amount] if hash[:id] == specific_id
  sum
end

Q2 part 1: calculate the sums per id

sums = array.inject(Hash.new(0)) do |sums, hash|
  sums[hash[:id]] += hash[:amount]
  sums
end

Q2 part 2: find id/sum for max sum

max = sums.inject(sums.first) do |max, pair|
  pair.last > max.last ? pair : max
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