neo-code
neo-code

Reputation: 1076

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]]

Upvotes: 3

Views: 700

Answers (3)

johnsyweb
johnsyweb

Reputation: 141780

This can be achieved with a combination of Array#zip and Array#map:

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

However, key-value pairs are often best treated as a Hash. Among other operations, this will allow you to #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}

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118261

Another approach as 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]]

Taking the help of merge(other_hash){|key, oldval, newval| block} .

Upvotes: 1

sawa
sawa

Reputation: 168081

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

Upvotes: 11

Related Questions