[英]Remove duplicates items from Hash
I have the following array of hashes 我有以下散列数组
input = [
{'line_number' => 1, 'name' => 'Name1', 'value' => 'Value'},
{'line_number' => 1, 'name' => 'Name2', 'value' => 'Value'},
{'line_number' => 2, 'name' => 'AnotherName', 'value' => 'AnotherValue'}
]
I want, which after checking for uniqueness the output would be 我想要,在检查唯一性之后,输出将是
output = [
{'line_number' => 1, 'name' => 'Name2', 'value' => 'Value'},
{'line_number' => 2, 'name' => 'AnotherName', 'value' => 'AnotherValue'}
]
because simple uniqueness 因为简单的独特性
input.uniq! { |i| i['line_number'] }give me 给我吗
output = [ {'line_number' => 1, 'name' => 'Name1', 'value' => 'Value'}, {'line_number' => 2, 'name' => 'AnotherName', 'value' => 'AnotherValue'} ]
Thanks in advance. 提前致谢。
If you want to keep the last one, you can do this 如果要保留最后一个,可以执行此操作
input.each_with_object({}) {|h, obj| obj[h['line_number']] = h}.values
# => [{"line_number"=>1, "name"=>"Name2", "value"=>"Value"},
# => {"line_number"=>2, "name"=>"AnotherName", "value"=>"AnotherValue"}]
这个问题很奇怪,但是也许可以帮助您:
input.group_by { |i| i['line_number'] }.values.map! { |i| i.last }
如果要保留最后一个而不是第一个,为什么不简单
input.reverse.uniq { |i| i['line_number'] }
input.each_with_object({}) { |g,h| h.update(g['line_number']=>g) }.values
#=> [{"line_number"=>1, "name"=>"Name2", "value"=>"Value"},
# {"line_number"=>2, "name"=>"AnotherName", "value"=>"AnotherValue"}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.