Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 want the following output.

result = [[1,20],[2,30],[3,15],[4,40]]
like image 208
neo-code Avatar asked Dec 28 '25 17:12

neo-code


1 Answers

[array1, array2].transpose.map{|(k, v1), (_, v2)| [k, v1 + v2]}
# => [[1, 20], [2, 30], [3, 15], [4, 40]]
like image 91
sawa Avatar answered Dec 31 '25 07:12

sawa