Remove duplicates from an array

后端 未结 1 779
生来不讨喜
生来不讨喜 2021-01-27 11:22

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(         


        
相关标签:
1条回答
  • 2021-01-27 11:50

    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.

    0 讨论(0)
提交回复
热议问题