Tries to display only duplicate values

I am trying to display only the duplicate value in an array that just contains the names.

So for example, my code is:

<%= s= arrayOfStuff %> <%= t= arrayOfStuff.uniq %> 

which displays

 ["UK01USV005", "NJ08APP516", "NJ08MHF001", "UK01USV505", "NY01MHF0006", "UK01USV525", "UK01USV005", "NJ08APP515", "NJ08MHF002"] ["UK01USV005", "NJ08APP516", "NJ08MHF001", "UK01USV505", "NY01MHF0006", "UK01USV525", "NJ08APP515", "NJ08MHF002"] 

so when I do st , it should give me a duplicate value, which in this case is equal to UK01USV005 , however the results that I get are an empty array that looks like this: [] .

Any ideas why this could be?

+4
source share
4 answers
 arrayOfStuff.group_by {|e| e}.select { |k,v| v.size > 1}.keys 

should work fine.

+10
source

You are 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 
+5
source

Subtracting an array from the array removes all matching objects, not just the first one.

See a simple test:

 [1,2,1] - [1] # => [2] 

So, if you want to scan duplicate values, you can try group_by (since lucapette was able to offer much faster); -)

+1
source

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"] 

What are you looking for?

0
source

Source: https://habr.com/ru/post/1369659/


All Articles