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

a5zima

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.

Sebi
[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.

edited at
0

Comments

0 comments
Login to comment

Related

What is the best way to merge 2 byte arrays?

What is the best way to merge nested arrays

compare element in two arrays

What's the best way to split an array into multiple arrays every time an element is met?

Best way to merge two Arrays of Classes based on Class variable value

Best way Merge two string arrays based on a condition

What is the best way to "merge" 2 arrays by each value?

Merge Two Arrays With Child elements

Merge each element from two arrays of object javascript

In Swift, what is the best way to assign two arrays to key/value of a dictionary?

What is the best way to combine two arrays using javascript?

Comparing each element in of two arrays

sum of two arrays element wise?

Sum two arrays element-by-element in Java

Merge two arrays in R alternating their elements

How to merge elements of two string arrays in javascript?

Merge two arrays in a sequential and structured way

What's the best way to merge to arrays based on key values in each array?

checking adjacent elements of an element in an array of arrays in java

What's the best way to document an array of arrays of arrays using JSDoc?

Is there a way to check if two arrays have the same elements?

Merge two arrays into an list of arrays

Find common element in two from three arrays

$or operation for matching the same element in two different arrays

JavaScript get common element in two arrays

Check if an element is included in two different arrays

Greater of two numpy arrays, element-wise

Compare each element in two arrays Swift

Numpy find identical element in two arrays