1

I'm trying to figure it out how I can remove duplicates from an ArrayList in VBScript, but there seems no information available on this. As (apparently) there is no dedicated function for this, maybe I could get some suggestions how it can be done otherwise?

The only similar questions I found were related to Java, not VBScript.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
derei
  • 193
  • 2
  • 4
  • 17
  • Possible duplicate of [How do I remove repeated elements from ArrayList?](https://stackoverflow.com/questions/203984/how-do-i-remove-repeated-elements-from-arraylist) – Gurmanjot Singh Jun 11 '17 at 05:41
  • @Kira this question is about VBScript, not about Java. Thanks for the possible answer, but it doesn't apply in this particular case. – derei Jun 11 '17 at 10:49
  • @derei What do you mean by `ArrayList`? There's no such a built-in object or type in VBScript. Could you show us a sample code? – Kul-Tigin Jun 11 '17 at 21:22
  • 1
    @Kul-Tigin He means the [`System.Collections.ArrayList`](https://msdn.microsoft.com/en-us/library/system.collections.arraylist.aspx) class. It's one of the .Net classes that expose a COM interface and can thus be used in VBScript. – Ansgar Wiechers Jun 12 '17 at 07:38
  • 1
    @AnsgarWiechers I know what it is. I often use those COM-visible .NET objects in VBScript especially the ones from `System.Collections` and `System.Security.Cryptography` namespace. But it's not the point. I asked because an example VB.NET code snippet taken from somewhere might brought us here. We'll see what he / she mans. – Kul-Tigin Jun 12 '17 at 08:14

2 Answers2

1

I'd say the simplest way is to put the values into a Dictionary:

Set d = CreateObject("Scripting.Dictionary")

For Each e In arrayList
  d(e) = e
Next

arr = d.Items    'put unique elements back into 

If your array list contains objects and you don't want the object reference as the uniqueness indicator you need to identify some kind of property (or combination of properties) that defines the uniqueness of your objects and use that as the key in the dictionary. You also need to use the Set keyword for assigning objects.

For Each e In arrayList
  Set d(e.uniqueProperty) = e
Next

If you want the unique list back in the original variable you need another loop to transfer the elements from the dictionary back to the array list:

arrayList.Clear
For Each e In d.Items
  arrayList.Add e
Next
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
1

Arraylist objects in vba have a .contains method. So, all you have to do to get an arraylist without duplicates is somthing like this.

Set newArraylist = CreateObject("Scripting.Dictionary")

For Each item In originalArrayList
  if newArraylist .contains(item) = false then newArraylist .add(item)
Next
gshep
  • 50
  • 5