【问题标题】:Unique array of hashes by key value按键值排列的唯一哈希数组
【发布时间】:2015-07-22 08:37:37
【问题描述】:

好的,所以...我有一个这样的哈希数组:

[
    { :id => 0, :text => "someText" },
    { :id => 1, :text => "anotherText" },
    { :id => 2, :text => "someText" }
]

我想要的是 filter 哈希并删除重复的 :text 值,因此结果是:

[
    { :id => 0, :text => "someText" },
    { :id => 1, :text => "anotherText" }
]

我该怎么做?


附:当然,我可以找到方法并做到这一点。鉴于我不是这样的 Ruby 大师,我要的是最好(和最快)的 Ruby 友好方式。 ;-)

【问题讨论】:

    标签: arrays ruby hash unique


    【解决方案1】:

    使用 Array#uniq 试试这个:

    arr.uniq{|h| h[:text]} # Returns a new array by removing duplicate values
     => [{:id=>0, :text=>"someText"}, {:id=>1, :text=>"anotherText"}]
    # OR    
    arr.uniq!{|h| h[:text]} # Removes duplicate elements from self.
    => [{:id=>0, :text=>"someText"}, {:id=>1, :text=>"anotherText"}]
    

    将有许多不同的方法来实现您的目标,但是当您正在寻找最快的方法时,这里是 uniqgroup_by 的基准。这仅用于示例。像这样,您可以测试自己的不同方法并根据您的要求检查解决方案..

    require 'benchmark'
    arr = [{ :id => 0, :text => "someText" }, { :id => 1, :text => "anotherText" }, { :id => 2, :text => "someText" }]
    Benchmark.bm do |x|
      x.report("group_by:")   { arr.group_by { |e| e[:text] }.values.map &:first }
      x.report("uniq:")   { arr.uniq{|h| h[:text]} }
    end
    # output
                user     system      total        real
    group_by:  0.000000   0.000000   0.000000 (  0.000039)
    uniq:      0.000000   0.000000   0.000000 (  0.000012)
    

    【讨论】:

    • 我认为应该对第二种情况给出公平的警告,因为它会改变数组本身的值。
    • @vjdhama :对不起,我没听懂你,但我已经对这两个案例发表了评论
    • @Dr.Kameleon :我的荣幸。很高兴为您提供帮助。
    【解决方案2】:

    虽然uniq 是解决问题的完美方案,但还有更灵活的方法,您可以指定从多个变体中挑选出的附加条件:

    #                                        ⇓⇓⇓⇓⇓⇓⇓
    arr.group_by { |e| e[:text] }.values.map &:first
    

    人们可能会在此处设置任何条件以仅选择具有:id 或其他内容的元素。

    【讨论】:

    • mudasobwa :我添加了基准测试只是为了明确最快的 OP 方法。我的目的不是证明你的方法是错误的,而我的方法是对的。所以请不要介意,不要误解我。无论如何,我很高兴知道这个新技巧:)
    猜你喜欢
    • 2014-10-27
    • 2011-02-15
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 2013-12-04
    • 2018-02-04
    相关资源
    最近更新 更多