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]]
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With