添加多维数组的值 - Adding values of multi dimensional array

- 此内容更新于:2016-02-02
主题:

我处理图表数据。我有三个来源的三组数据,我试图把它们加在一起一年到一个新的。在我的例子中,多年来都是0,1,2。与实际数据视觉:这是一个例子:我试图得到以下结果:增加复杂性,它不会总是三组数据,它可能是一组或十二集,任何数字。非常感谢您的帮助。

原文:

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.

网友:告诉我们你有试过的代码

(原文:show us the code you have tried)

解决方案:
解决方案:解释:步骤1:将数据数组转换成一系列的散列步骤2:减少通过合并每个哈希散列的数组,同时确保为给定键值加在一起。我们使用空哈希的初始值,并合并每个哈希在数组——块将确保关键被合并时,其值加起来,这样最终我们得到的所有值的总和,关键步骤3:使用散列数组结果
原文:

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]]
网友:非常感谢你的解释。

(原文:Thank you very much for the explanation.)