Array add only duplicate

Hello,

i have an array with several duplicate entries and i only want the duplicates to add to a listbox.

this is my sad try but its missing entries of course:

for i as integer=  window1.products.LastIndex DownTo 0
  if i>0 then
    if window1.products(i).NthField(";#!",2)=window1.products(i-1).NthField(";#!",2) and window1.products(i).NthField(";#!",2)<>"" then
listbox.addrow window1.products(i)
    end if
  end if 
next

any suggestions please… :laughing:
Marco

Are the duplicates next to each other ? If not then for sure you will miss some.

Myarray.sort

var previousString as string

For i as integer = 0 to MyArray.ubound-1
  if MyArray(i) = previousString then Listbox1.addrow(MyArray(i)) // Add only the duplicate
  previousString = MyArray(i)
next

Create a Dictionary that holds a count of each unique entry, then cycle through the Dictionary and add only those items to your Listbox where the count >= 2.

var counter as new Dictionary
for each item as string in window1.Products
  var key as string = item.NthField(";#!", 2)
  counter.Value(key) = counter.Lookup(key, 0).IntegerValue + 1
next
3 Likes

Your code says that they are already in the listbox.
Its easier to de-dupe before you populate the box.

Instead of

for x = 0 to whatever
//add to list box
next
//panic because there are duplicates

if you are using a database , SELECT DISTINCT from it

if not, use a dictionary


for x = 0 to whatever
mydictionary.value(  thing(x) ) = "."
next

for each k in mydictionary.keys
//add to listbox
next

I think this is probably more efficient:

var counter as new Dictionary
for each item as string in window1.Products
  var key as string = item.NthField(";#!", 2)

  if not(counter.KeyExists(key)) then
     counter.value(key)=true
   else
      'Handle duplicate item
   end
next

Probably, but we’d have to test.

BTW, you don’t have to assign anything to the Value. Nil will do it.

Yet another method:

for i as integer=0 to MyArray.LastIndex
Var IsDuplicate As Boolean=MyArray.IndexOf(MyArray(i),i+1)>-1

if IsDuplicate then AddToListBox
next

If an item appears three times in the array, that code will add it to the Listbox twice.

1 Like

Yes. I expected the original poster wanted to see one entry per duplicate. It was not specified.