X
X
xxx44yyy2019-03-09 21:58:25
ruby
xxx44yyy, 2019-03-09 21:58:25

How to concatenate three arrays of hashes?

There are three arrays

[
   { year: 2000, a: 10},
   { year: 2001, a: 20}
]

[
   { year: 2000, b: 100},
   { year: 2001, b: 200}
]

[
   { year: 2000, c: 1000},
   { year: 2001, c: 2000}
]

I want to get this:
[
   { year: 2000, a: 10, b: 100, c: 1000},
   { year: 2001, a: 20, b: 200, c: 2000}
]

How to do it? merge did not help :(

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2019-03-09
@xxx44yyy

a.map.with_index{|n, i| n.merge(b[i]).merge(c[i])}
or, if it is not guaranteed that the number of elements and their order are the same:

(a + b + c).group_by{|n| n[:year]}.map{|i, n| n.reduce({}, :merge)}

R
Roman Mirilaczvili, 2019-03-09
@2ord

Select the 1st array as target.
Going through the elements of the 2nd in each of them extract the year (key :year) and find the first occurrence in the 1st. It is with him that you need to merge.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question