ruby 如何获取数组中每个重复项的第一个匹配项?

lsmepo6l  于 2023-03-01  发布在  Ruby
关注(0)|答案(2)|浏览(144)

我有一个对象数组:

array =
[{:id=>433, :name=>"test 1", :type=>"Staff"},
 {:id=>434, :name=>"test 2", :type=>"Guard"},
 {:id=>435, :name=>"test 3", :type=>"Office boy"},
 {:id=>471, :name=>"test 1", :type=>"Staff"},
 {:id=>473, :name=>"test 2", :type=>"Guard"}]

有些:type值出现了不止一次,对于每个重复的:type值,我想检索该类型的第一个对象。
预期输出为:

[{:id=>433, :name=>"test 1", :type=>"Staff"},
 {:id=>434, :name=>"test 2", :type=>"Guard"}]

不包括类型为"Office boy"的散列,因为该类型只出现一次。

oxcyiej7

oxcyiej71#

array = [{ :id => 433, :name => "test 1", :type => "Staff" },
         { :id => 434, :name => "test 2", :type => "Guard" },
         { :id => 435, :name => "test 3", :type => "Office boy" },
         { :id => 471, :name => "test 1", :type => "Staff" },
         { :id => 473, :name => "test 2", :type => "Guard" }]

result = array.group_by { |hash| hash[:type] }.values.filter_map do |value|
  value.first if value.count > 1
end

p result

产出

[{:id=>433, :name=>"test 1", :type=>"Staff"}, {:id=>434, :name=>"test 2", :type=>"Guard"}]
qzwqbdag

qzwqbdag2#

下面是使用Enumerable #计数的方法。

types_count = array.map { |h| h[:type] }.tally
  #=> {"Staff"=>2, "Guard"=>2, "Office boy"=>1}
array.select do |h|
  type = h[:type]
  keep = types_count[type] > 1
  types_count[type] = 0
  keep
end
  #=> [{:id=>433, :name=>"test 1", :type=>"Staff"},
  #    {:id=>434, :name=>"test 2", :type=>"Guard"}]

相关问题