How to add two multidimensional arrays

I want to do the following:

array1 = [[1, 10], [2, 20], [3, 10], [4, 30]]
array2 = [[1, 10], [2, 10], [3, 5], [4, 10]]

I want to add two arrays in such a way that the second element of each subarray will be added. I need the following conclusion.

result = [[1,20],[2,30],[3,15],[4,40]]
+3
source share
3 answers
[array1, array2].transpose.map{|(k, v1), (_, v2)| [k, v1 + v2]}
# => [[1, 20], [2, 30], [3, 15], [4, 40]]
+11
source

Another approach as shown below:

array1 = [[1,10],[2,20],[3,10],[4,30]]
array2 = [[1,10],[2,10],[3,5],[4,10]]

Hash[array1].merge(Hash[array2]) { |key,old,new| old + new }.to_a
# => [[1, 20], [2, 30], [3, 15], [4, 40]]

Using merge(other_hash){|key, oldval, newval| block}.

+1
source

Array#zip Array#map:

result = array1.zip(array2).map { |l, r| [l[0], l[1] + r[1]] }
#=> [[1, 20], [2, 30], [3, 15], [4, 40]]

- Hash. #merge:

hash1
#=> {1=>10, 2=>20, 3=>10, 4=>30}
hash2
#=> {1=>10, 2=>10, 3=>5, 4=>10}
result = hash1.merge(hash2) { |_, l, r| l + r }
#=> {1=>20, 2=>30, 3=>15, 4=>40}
0

Source: https://habr.com/ru/post/1531100/


All Articles