I have an array containing hashes, like this:
[
{:id => 1, :week => 1, :year => 2014},
{:id => 2, :week => 2, :year => 2014},
{:id => 1, :week => 1, :year => 2015},
{:id => 2, :week => 5, :year => 2015},
]
What i need is a array of arrays, containing each two values: The first value is a hash from the first array with year 2014, the second is a hash from the first array with year 2015, if it has the same week and id as the first hash.
If there is not hash with equal id and week from 2015, then the second value has to be nil, vice versa the first value is nil.
For the array above, the new array should look like:
[
[{:id => 1, :week => 1, :year => 2014}, {:id => 1, :week => 1, :year => 2015}],
[{:id => 2, :week => 2, :year => 2014}, nil],
[nil, {:id => 2, :week => 5, :year => 2015}],
]
-e- my approach:
result = []
all_ids.each do |id|
all_weeks.each do |week|
v1 = array.select{ |v| v.id == id && v.week == week && v.year == 2014}
v2 = array.select{ |v| v.id == id && v.week == week && v.year == 2015}
v1 = v1.length == 1 ? v1.first : nil
v2 = v2.length == 1 ? v1.first : nil
result << [v1, v2]
end
end
this doesn't seem to be very efficient as i have to iterate the array multiple times
a.group_by { |el| [el[:id], el[:week]] }might be a good way to go.