Search code examples
ruby-on-railsrubyruby-hash

Hash unique by column and merge other column


I have below hash. How to get unique and merged hash.

[
 {
  "email"=>"[email protected]",
  "expression"=>"aaa",
  "name"=>"bbb",
  "roles"=>[:admin]
  },

  {
   "email"=>"[email protected]",
   "expression"=>"aaa",
   "name"=>"bbb",
   "roles"=>[:manager]
  }
]

I want below result hash that unique by email and merged by roles.

[
  {
    "email"=>"[email protected]",
    "expression"=>"aaa",
    "name"=>"bbb",
    "roles"=>[:admin, :manager]
  }
]

Help me.


Solution

  • Try this one

    a.group_by { |item| item["email"] }.each_with_object([]) do |(_, items), arr| 
      arr.concat([items.first.merge("roles" => items.flat_map { |item| item["roles"] }.uniq)])
    end