Grouping an array based on its first element without duplication in Ruby

I am running the active write command Product.pluck (: category_id ,: price) which returns an array of 2 arrays of items:

[
  [1, 500],
  [1, 100],
  [2, 300]
]

      

I want to group by the first element by creating a hash that looks like this:

{1 => [500, 100], 2 => [300]}

      

group_by seems logical, but replicates the entire array. That is, a.group_by (&: first) produces:

{1=>[[1, 500], [1, 100]], 2=>[[2, 300]]}

      

+3


source to share


3 answers


You can do a secondary conversion for it:

Hash[
  array.group_by(&:first).collect do |key, values|
    [ key, values.collect { |v| v[1] } ]
  end
]

      



Alternatively, just draw the logic directly:

array.each_with_object({ }) do |item, result|
  (result[item[0]] ||= [ ]) << item[1]
end

      

+12


source


Since you are grouping the first element, just remove it with shift

and turn the result into a hash:



array.group_by(&:first).map do |key, value|
  value = value.flat_map { |x| x.shift; x }
  [key, value]
end #=> {1=>[500, 100], 2=>[300]}

      

+3


source


This one line frame seemed to work for me.

array.group_by(&:first).map { |k, v| [k, v.each(&:shift)] }.to_h

      

+2


source







All Articles