Add values of same Key in array of hashes

放肆的年华 提交于 2019-12-11 11:25:14

问题


Trying to add values of same key but with iterating it. here is my array

arr = [ {a: 10, b: 5, c: 2}, {a: 5, c: 3}, { b: 15, c: 4}, {a: 2}, {} ]

Want to converted it like

{a: 17, b: 20, c: 9} 

回答1:


Here is one way to do this by making use of Enumerable#reduce and Hash#merge:

arr.reduce {|acc, h| acc.merge(h) {|_,v1,v2| v1 + v2 }}
#=> {:a=>17, :b=>20, :c=>9}



回答2:


each_with_object to the rescue:

result = arr.each_with_object(Hash.new(0)) do |hash, result|
  hash.each { |key, value| result[key] += value}
end

p result



回答3:


#1 Use a "counting hash"

Edit: I just noticed that @Pascal posted the same solution earlier. I'll leave mine for the explanation.

arr.each_with_object(Hash.new(0)) { |h,g| h.each { |k,v| g[k] += v } }
  #=> {:a=>17, :b=>20, :c=>9} 

h = Hash.new(0) is a counting hash with a default value of zero. That means that if h does not have a key k, h[k] returns zero (but the hash is not altered). Ruby expands h[k] += 4 to h[k] = h[k] + 4, so if h does not have a key k, h[k] on the right side of the equality equals zero.

#2 Use Hash#update

Specifically, use the form of this method (aka merge!) that employs a block to determine the values of keys that are present in both hashes being merged.

arr.each_with_object({}) { |h,g| g.update(h) { |_,o,n| o+n } }
  #=> {:a=>17, :b=>20, :c=>9} 


来源:https://stackoverflow.com/questions/36004998/add-values-of-same-key-in-array-of-hashes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!