0

How can I remove duplicates from an array in vbscript?

Code:

     dim XObj(100),xObjXml
      for s=0 to xObjXml.length-1      
      XObj(s)=xObjXml(s).getAttribute("xsx")
      next

Please suggest a better answer for this.

0m3r
  • 11,696
  • 15
  • 30
  • 65
user1495475
  • 997
  • 3
  • 17
  • 33

2 Answers2

3

Use a Dictionary to gather the unique items of the array:

>> a = Array(1, 2, 3, 1, 2, 3)
>> WScript.Echo Join(a)
>> Set d = CreateObject("Scripting.Dictionary")
>> For i = 0 To UBound(a)
>>     d(a(i)) = d(a(i)) + 1
>> Next
>> WScript.Echo Join(d.Keys())
>>
1 2 3 1 2 3
1 2 3
>>

(BTW: There is no .length property for VBScript arrays)

Added:

The .Keys() method of the dictionary returns an array of the (unique) keys:

>> b = d.Keys()
>> WScript.Echo Join(b), "or:", b(2), b(1), b(0)
>>
1 2 3 or: 3 2 1

Added II: (aircode!)

Trying to get the unique attributes of the objects in an XML collection:

Dim xObjXml  : Set xObjXml  = ... get some collection of XML objects ...
Dim dicAttrs : Set dicAttrs = CreateObject("Scripting.Dictionary")
Dim i
For i = 0 To xObjXml.length - 1                 
    Dim a : a = xObjXml(i).getAttribute("xsx")  
    dicAttrs(a) = dicAttrs(a) + 1
Next
Dim aAttrs : aAttrs = dicAttrs.Keys()

Added III (sorry!):

.Keys() is a method, so it should be called as such:

Dim aAttrs : aAttrs = dicAttrs.Keys()

Added IV:

For a working sample see here.

Community
  • 1
  • 1
Ekkehard.Horner
  • 37,907
  • 2
  • 42
  • 88
0

If you don't want a Dictionary you can use the following to compare each element in the array to itself.

Info = Array("Arup","John","Mike","John","Lisa","Arup")

x = 0
z = ubound(Info)
Do
x = x + 1
Do
z = z - 1
If x = z Then
Info(x) = Info(z)
ElseIf Info(x) = Info(z) Then
Info(x) = ""
End If
Loop Until z=0
z = ubound(Info)
Loop Until x = ubound(Info)
For each x in Info 
If x <> "" Then
Unique = Unique & Chr(13) & x
End If
Next

MsgBox Unique
Moir
  • 369
  • 4
  • 13