I'm trying to display only the duplicate value in an array which just holds names.
So for instance, my code is:
<%= s= arrayOfStuff %>
<%= t= arrayOfStuff.uniq %>
which displays
["UK01USV005", "NJ08APP516", "NJ08MHF001", "UK01USV505", "NY01MHF0006", "UK01USV525", "UK01USV005", "NJ08APP515", "NJ08MHF002"]
["UK01USV005", "NJ08APP516", "NJ08MHF001", "UK01USV505", "NY01MHF0006", "开发者_JAVA技巧UK01USV525", "NJ08APP515", "NJ08MHF002"]
so theortically when I do s-t
it should give me the duplicate value which in this case is UK01USV005
, however the results I get is an empty array which obviously looks like this: []
.
Any ideas why that could be?
arrayOfStuff.group_by {|e| e}.select { |k,v| v.size > 1}.keys
should work fine.
You're wrong.
["a", "a", "a"] - ["a"]
#=> []
You can try this in your case:
a.inject([]){|ar, item| b.include?(item) ? b.delete(item) : ar << item; ar}
#=> ["UK01USV005"]
or with your original Array
arrayOfStuff.select{|item| arrayOfStuff.count(item) > 1}.uniq
Subtracting an array from an array removes all the matching objects, not only the first one.
See the simple test:
[1,2,1] - [1] # => [2]
So, if you want to scan for duplicate values, you may try group_by
(as lucapette managed to suggest much faster) ;-)
You can do something like:
["UK01USV005", "NJ08APP516", "NJ08MHF001", "UK01USV505", "NY01MHF0006", "UK01USV525", "NJ08APP515", "NJ08MHF002"] && ["UK01USV005", "NJ08APP516", "NJ08MHF001", "UK01USV505", "NY01MHF0006", "UK01USV525", "UK01USV005", "NJ08APP515", "NJ08MHF002"]
=> ["UK01USV005", "NJ08APP516", "NJ08MHF001", "UK01USV505", "NY01MHF0006", "UK01USV525", "UK01USV005", "NJ08APP515", "NJ08MHF002"]
Which is what you are looking for?
精彩评论