PDD PDD - 1 month ago 5
Ruby Question

Combine first elements of multidimensional array

Let's say I have an array of product IDs and Quantities, like this:

records = [[1, 10], [1, 30], [4, 10], [4, 100], [5, 45]]


What's the easiest/most efficient way in Ruby to achieve a hash of the combined products and quantities, like this?

products_needed = [{id: 1, count:40}, {id: 4, count: 110}, {id:5, count:45}]

Answer Source

Try this:

records.group_by(&:first).map do |id, records_for_id|
  {
     id: id,
     count: records_for_id.sum(&:last)
  }
end