What is the best way to merge two arrays (element + element), if elements itself are arrays

Viewed 117

I have two nested arrays with equal size:

Array1 =[[1, 2], [], [2, 3]]
Array2= [[1, 4], [8, 11], [3, 6]]

I need to merge them in one array, like this:

Array = [[1,2,1,4], [8,11], [2,3,3,6]],

so each elements of new Array[x] = Array1[x] + Array2[x]

I understand how to do it with for(each) cycle, but I am sure Ruby has an elegant solution for that. It is also possible that the solution will produce by changing Array1.

3 Answers
Array1.each_index.map { |i| Array1[i] + Array2[i] }
  #=> [[1,2,1,4], [8,11], [2,3,3,6]]

This has the advantage that it avoids the creation of a temporary array [Array1, Array2].transpose or Array1.zip(Array2).

[Array1, Array2].transpose.map(&:flatten) 
=> [[1, 2, 1, 4], [8, 11], [2, 3, 3, 6]]

RubyGuides: "Turn Rows Into Columns With The Ruby Transpose Method"


Each step explained:

[Array1, Array2]
=> [[[1, 2], [], [2, 3]], 
    [[1, 4], [8, 11], [3, 6]]]

Create a grid like array.

[Array1, Array2].transpose
=> [[[1, 2], [1, 4]], [[], [8, 11]], [[2, 3], [3, 6]]]

transpose switches rows and columns (close to what we want)

[Array1, Array2].transpose.map(&:flatten)
=> [[1, 2, 1, 4], [8, 11], [2, 3, 3, 6]]

flatten gets rid of the unnecessary nested arrays (here combined with map to access nested arrays)

I would do something like:

array1 =[[1, 2], [], [2, 3]]
array2= [[1, 4], [8, 11], [3, 6]]

array1.zip(array2).map(&:flatten)
# => [[1, 2, 1, 4], [8, 11], [2, 3, 3, 6]]
Related