简体   繁体   中英

how to group by in a array of hashes

I have a array of hashes

and I need to be able to group them by users.

      order = Order.find(options[:order_id])
      shipments = order.shipments.select {|shipment| shipment["roundtrip_shipment"] == nil }.collect {|o| {
        id: o.id,
        user_id: o.user_id,
        ...
      } }

I am having some problems in making a group by in the array.

I have tried to do shipments = order.shipments.group_by { |shipment| shipment[:user_id] }.count shipments = order.shipments.group_by { |shipment| shipment[:user_id] }.count

but this always returns 1 when I know that have 2 users here Thanks for all the help

You can simply do as follow:

order = Order.find(options[:order_id])
shipments = order.shipments.where.not(roundtrip_shipment: nil).group_by(&:user_id).collect {|x,y| {x => y.map(&:id)} }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM