英文:
How to get first occurrence of each duplicate in an array?
问题
我有一个对象数组:
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" 的哈希,因为该类型只出现一次。
英文:
I have an array of objects:
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"}]
Some :type
values occur more than once. For each duplicate :type
value, I want to retrieve that type's first object.
The expected output is:
[{:id=>433, :name=>"test 1", :type=>"Staff"},
{:id=>434, :name=>"test 2", :type=>"Guard"}]
A hash with type "Office boy" is not included because that type only occurs once.
答案1
得分: 3
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
Output
[{:id=>433, :name=>"test 1", :type=>"Staff"}, {:id=>434, :name=>"test 2", :type=>"Guard"}]
英文:
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
Output
[{:id=>433, :name=>"test 1", :type=>"Staff"}, {:id=>434, :name=>"test 2", :type=>"Guard"}]
答案2
得分: 1
这里是使用Enumerable#tally的一种方法。
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"}]
英文:
Here's a way that uses Enumerable#tally.
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"}]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论