Wednesday, 7 December 2016

Merge subarrays into single one and remove duplicates if they have same id using ruby on rails

I have an array of arrays like this:
array = [[1, 'Something', '123456321'], [2, 'Something', '123456321'], [2, 'Something', 1234563212']]
And I want to merge the subarrays that have same id and get this result:
array = [[1, 'Something', '123456321'], [2, 'Something, Something', '123456321, 1234563212']]
Can anyone help me? Thanks!


Best Answer;



array.group_by(&:first).map do |id, records|
  names  = records.map(&:second).join(', ')
  values = records.map(&:last).join(', ')

  [id, names, values]
end

As you asked the reversed question recently, I suggest you to read the EnumerableArrayHashand String documentations. It will give you an instant boost in expressiveness and understanding of how to do common tasks with Ruby.


No comments:

Post a Comment