1

I have these arrays of arrays :

array0 = [["1"], ["2"], ["3"],…]

array1 = [["a"], ["b"], ["c"],…]

array2 = [["pap"], ["pop"], ["pip"],…]

I want to push every element in every array, to the first array so the output should be:

output = [["1", "a", "pap"], ["2", "b", "pop"], ["3", "c" ,"pip"]]

2 Answers 2

4

First do flatten on each array to get single dimension array. Then use zip to get 2-dimension array each having 3-elements

array0.flatten.zip(array1.flatten, array2.flatten)

Shorter way of doing the same: (Solution given by @Ivaylo Strandjev)

array0.zip(array1, array2).map(&:flatten)
Sign up to request clarification or add additional context in comments.

4 Comments

+1 Never noticed I should flatten the result. Still you can do it in a shorter manner, take a look at my answer.
@Mehdi Kumar Ivaylo Strandjev solution is good.. Use that :)
@checkit Thanks that helped a lot. I actually meant to make it 2-dimensional because I thought it will be more easier with it. But I see that I don't need that. an a.zip() will do the job. Thank you
@checkit thank you but in fact you were the first one to provide a working solution. So you deserve the accept. Still maybe edit your answer to suggest the shorter version for future generations.
2

Try this:

 array0.zip(array1).zip(array2).map(&:flatten)

Also you can do it with a single zip:

 array0.zip(array1, array2).map(&:flatten)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.