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
.
[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)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments