0

I Have 2 arrays such as:

arr1 : {[:day => 12, :sum_src => 1234], [:day => 14, :sum_src => 24543]}
arr2 : {[:day => 12, :sum_dst => 4234], [:day => 14, :sum_dst => 342334]}

I want to merge this two arrays into one, so that it looks like:

arr3 : {[:day => 12, :sum_src => 1234, :sum_dst => 4234],[:day => 14, :sum_src => 24543, :sum_dst => 342334]}

Is it possible? And how to do this ?

2
  • that doesnt look like an array to me, hashes? Commented Sep 15, 2011 at 13:42
  • I have fixed my first message Commented Sep 15, 2011 at 14:02

3 Answers 3

1

Riffing off Qerub's answer - if the arrays are sorted as in the example zip can be a great tool for this:

arr1 = [{:day => 12, :sum_src => 1234}, {:day => 14, :sum_src => 24543}]
arr2 = [{:day => 12, :sum_dst => 4234}, {:day => 14, :sum_dst => 342334}]
arr1.zip(arr2).map {|a,b| a.merge!(b)}

Result

[{:day=>12, :sum_dst=>4234, :sum_src=>1234}, {:day=>14, :sum_dst=>342334, :sum_src=>24543}]
Sign up to request clarification or add additional context in comments.

Comments

0

Like Omar pointed out, those are hashes. If you have two hashes:

h1 = { "a" => 100, "b" => 200 }
h2 = { "b" => 254, "c" => 300 }
h1.merge(h2)   #=> {"a"=>100, "b"=>254, "c"=>300}

In your case, if you want to merge to arrays and remove repetitions, I would use Union operator:

[ "a", "b", "c" ] | [ "c", "d", "a" ] #=> [ "a", "b", "c", "d" ]

Taken from Rails API. Good luck!

1 Comment

<%@sum_all = @sum_dst.merge(@sum_src)%> undefined method `merge' for [#<Dst >, #<Dst >]:Array
0

(You have mixed up the syntaxes for literal hashes and arrays, but anyway…)

Here's a short but slightly cryptic solution:

arr1 = [{:day => 12, :sum_src => 1234}, {:day => 14, :sum_src => 24543}]
arr2 = [{:day => 12, :sum_dst => 4234}, {:day => 14, :sum_dst => 342334}]

result = (arr1 + arr2).inject({}) { |mem, x|
  (mem[x[:day]] ||= {}).merge!(x); mem
}.values

Result:

[{:sum_dst=>4234, :day=>12, :sum_src=>1234}, {:sum_dst=>342334, :day=>14, :sum_src=>24543}]

A more readable version would probably have more explicit looping. (Left for the reader as an exercise.)

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.