Ruby Merging Two Arrays into One

Ruby - Merge two arrays and remove values that have duplicate

You can do the following!

# Merging
c = a + b
=> [1, 2, 3, 4, 5, 2, 4, 6]
# Removing the value of other array
# (a & b) is getting the common element from these two arrays
c - (a & b)
=> [1, 3, 5, 6]

Dmitri's comment is also same though I came up with my idea independently.

Merge arrays in Ruby/Rails

Like this?

⚡️ irb
2.2.2 :001 > [1,2,3] + [4,5,6]
=> [1, 2, 3, 4, 5, 6]

But you don't have 2 arrays.

You could do something like:

@movie = Movie.first()
@options = Movie.order("RANDOM()").first(3).to_a << @movie

Merge and interleave two arrays in Ruby

You can do that with:

a.zip(s).flatten.compact

How to merge two array objects in ruby?

array1 = [{ID:"1",name:"Dog"}]
array2 = [{ID:"2",name:"Cat"}]
p array1 + array2
# => [{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}]

Or maybe this is superfluous:

array1 = [{ID:"1",name:"Dog"}]
array2 = [{ID:"2",name:"Cat"}]
array3 = [{ID:"3",name:"Duck"}]

p [array1, array2, array3].map(&:first)
# => [{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}, {:ID=>"3", :name=>"Duck"}]

Merge 2 arrays into same index value

Use zip and join:

array_1.zip(array_2).map { |a| a.join(' ') }

How to merge two arrays of hashes

uniq would work if you concatenate the arrays in reverse order:

(b + a).uniq { |h| h[:key] }
#=> [
# {:key=>1, :value=>"bar"},
# {:key=>1000, :value=>"something"},
# {:key=>2, :value=>"baz"}
# ]

It doesn't however preserve the order.

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

[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)



Related Topics



Leave a reply



Submit