Merge or sum 2 arrays on "keys" in ruby

You could do it thusly:

(a + b).group_by(&:first).map { |k, v| [k, v.map(&:last).inject(:+)] }

First you put the arrays together with + since you don't care about a and b, you just care about their elements. Then the group_by partitions the combined array by the first element so that the inner arrays can easily be worked with. Then you just have to pull out the second (or last) elements of the inner arrays with v.map(&:last) and sum them with inject(:+).

For example:

>> a = [[1,10],[2,20],[3,30]]
>> b = [[1,50],[3,70]]
>> (a + b).group_by(&:first).map { |k,v| [k, v.map(&:last).inject(:+)] }
=> [[1, 60], [2, 20], [3, 100]]

You can also do it the hash way:

Hash[a].merge(Hash[b]){|k,a,b|a+b}.to_a

Tags:

Arrays

Ruby

Sum