Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge or sum 2 arrays on "keys" in ruby

Tags:

arrays

ruby

sum

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]]
like image 850
Agush Avatar asked Feb 17 '12 18:02

Agush


1 Answers

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]]
like image 66
mu is too short Avatar answered Oct 12 '22 03:10

mu is too short