What's the fastest/one-liner way to remove duplicates in an array of objects, based on a specific key:value, or a result returned from a method?
For instance, I have 20 XML Element nodes that are all the same name, but they have different "text" values, some of which are duplicates. I would like to remove the duplicates by saying "if element.text == previous_element.text, remove it". How do I do that in Ruby in the shortest amount of code?
I've seen how to do it for simple string/integer values, but not for objects.
Here's the standard hashy way. Note the use of ||=
operator, which is a more convenient (a ||= b
) way to write a = b unless a
.
array.inject({}) do |hash,item|
hash[item.text]||=item
hash
end.values.inspect
You can do it in a single line either.
The script needs O(n) equality checks of text
strings. That's what's covered under O(n) when you see a hash.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With