Reputation: 5116
This is the array version of: Sum 2 hashes attributes with the same key
I have 2 arrays, for example:
a = [[1,10],[2,20],[3,30]]
b = [[1,50],[3,70]]
How can i sum each on the first value (if it exists) to get:
c = [[1,60],[2,20],[3,100]]
Upvotes: 8
Views: 2370
Reputation: 434615
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]]
Upvotes: 12
Reputation: 18530
You can also do it the hash way:
Hash[a].merge(Hash[b]){|k,a,b|a+b}.to_a
Upvotes: 10