1

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.

1
  • show us the code you have tried Commented Jan 30, 2016 at 19:01

1 Answer 1

4

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for the explanation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.