如何仅根据键从哈希数组中删除重复项?
您将如何根据键删除重复项?
values = [{"a"=>"1"}, {"a"=>"2"}, {"b"=>"1"}, {"a"=>"4"}]
如何忽略该值并基于 key 运行 uniq
以便它返回:
[{'a' => '1'}, {'b' => '1'}]
How would you go about removing duplicates based on the key?
values = [{"a"=>"1"}, {"a"=>"2"}, {"b"=>"1"}, {"a"=>"4"}]
How can I ignore the value and run uniq
based on key so that it returns:
[{'a' => '1'}, {'b' => '1'}]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您不关心哪个值被破坏,只需将它们运行到哈希中(它确实具有唯一的键,因此可能是这种情况下正确的集合类):
...或者如果您想要每个键的第一个:
如果你想返回一个数组:
Assuming you don't care which value gets clobbered, just run them into a hash (which does have unique keys and is therefore probably the right collection class for this case):
... or if you want the first of each key:
If you want to get back to a Array:
以下内容仅适用于 ruby 1.9,因此可能没用。
如果您需要按原来的顺序,
The following will work only in ruby 1.9, so it might be useless.
If you need it in the original order,
在不引入任何中间变量的情况下,下面的 1 行将达到目的:
Without introducing any intermediate variables the following 1 liner will do the trick: