jBeas
jBeas

Reputation: 926

Adding values of multi dimensional array

I'm working with chart data. I have three sets of data from three sources, and I'm trying to add them together by their year into a new away. In my example, the years are 0, 1, 2.

visual:

data = [[[year, value], [year, value], [year, value]],
       [[year, value], [year, value], [year, value]],
       [[year, value], [year, value], [year, value]]]

Here is an example with actual data:

data = [[[0, 1], [1, 2], [2, 3]],
       [[0, 4], [1, 5], [2, 6]],
       [[0, 7], [1, 8], [2, 9]]]

I'm trying to get the following result:

data = [[0, 12], [1, 15], [2, 18]]

To add to complexity, it won't always be three sets of data, it may be one set or twelve sets, any number.

Any help is greatly appreciated.

Upvotes: 1

Views: 45

Answers (1)

Wand Maker
Wand Maker

Reputation: 18762

Solution:

data.map(&:to_h).reduce({}) {|memo, h| memo.merge(h) {|_,v1,v2| v1 + v2} }.to_a

Explanation:

Step 1: Convert the data array into array of hashes

data_hash = data.map(&:to_h)
#=> [{0=>1, 1=>2, 2=>3}, {0=>4, 1=>5, 2=>6}, {0=>7, 1=>8, 2=>9}]

Step 2: Reduce the array of hash by merging each hash with one another, while ensuring that values are added together for a given key.

reduced_hash = data_hash.reduce({}) {|memo, h| memo.merge(h) {|_,v1,v2| v1 + v2} }  
#=> {0=>12, 1=>15, 2=>18}

We use empty hash {} as initial value of memo, and merge each hash present in data_hash array with it - the block to merge will ensure that when a key is being merged, its values are added up so that eventually we end up with sum of all values of that key

Step 3: Use to_a on the hash to get array result

 reduced_hash.to_a
 #=> [[0, 12], [1, 15], [2, 18]]

Upvotes: 4

Related Questions