How to remove duplicates in a hash in Ruby on Rails?

后端 未结 4 1654
眼角桃花
眼角桃花 2020-12-15 23:39

I have a hash like so:

[
  {
    :lname => \"Brown\",
    :email => \"james@intuit.com\",
    :fname => \"James\"
  },
  {
    :lname => nil,
            


        
4条回答
  •  我在风中等你
    2020-12-16 00:28

    I know this is an old thread, but Rails has a method on 'Enumerable' called 'index_by' which can be handy in this case:

    list = [
      {
        :lname => "Brown",
        :email => "james@intuit.com",
        :fname => "James"
      },
      {
        :lname => nil,
        :email => "brad@intuit.com",
        :fname => nil
      },
      {
        :lname => "Smith",
        :email => "brad@intuit.com",
        :fname => "Brad"
      },
      {
        :lname => nil,
        :email => "brad@intuit.com",
        :fname => nil
      },
      {
        :lname => "Smith",
        :email => "brad@intuit.com",
        :fname => "Brad"
      },
      {
        :lname => nil,
        :email => "brad@intuit.com",
        :fname => nil
      }
    ]
    

    Now you can get the unique rows as follows:

    list.index_by {|r| r[:email]}.values
    

    To merge the rows with the same email id.

    list.group_by{|r| r[:email]}.map do |k, v|
      v.inject({}) { |r, h| r.merge(h){ |key, o, n| o || n } }
    end
    

    Custom but efficient method:

    list.inject({}) do |r, h| 
      (r[h[:email]] ||= {}).merge!(h){ |key, old, new| old || new }
      r
    end.values
    

提交回复
热议问题