Results 1 to 11 of 11

Thread: Removing duplicates from an array

Threaded View

  1. #1

    Thread Starter
    Retired VBF Adm1nistrator plenderj's Avatar
    Join Date
    Jan 2001
    Location
    Dublin, Ireland
    Posts
    10,359

    Removing duplicates from an array

    How to remove duplicated items in an array.
    This is (in my opinion) a very fast way of doing it.

    I don't know of any faster methods.
    If you need to remove duplicated items from an array of a different type, then just adjust the code accordingly.

    Note: You will need to add a reference to "Microsoft Scripting Runtime" as the code uses its Dictionary object.
    To do this, select Project from the toolbar, then select "References", and then select "Microsoft Scripting Runtime"

    VB Code:
    1. Option Explicit
    2.  
    3. Private Sub removeDuplicates(ByRef arrName() As Long)
    4.     Dim i As Long, tempArr() As Long: ReDim tempArr(UBound(arrName))
    5.     Dim d As New Dictionary, n As Long
    6.     For i = 0 To UBound(arrName)
    7.         If Not d.Exists(arrName(i)) Then
    8.             d.Add arrName(i), arrName(i)
    9.             tempArr(n) = arrName(i): n = n + 1
    10.         End If
    11.     Next
    12.     ReDim Preserve tempArr(n)
    13.     arrName = tempArr
    14. End Sub
    15.  
    16. Private Sub Form_Load()
    17.     Dim x() As Long, i As Long: ReDim x(99)
    18.    
    19.     '' this loop will fill the array with values :
    20.     '' 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3...
    21.     ''
    22.     For i = 0 To 99
    23.         x(i) = i Mod 4
    24.     Next
    25.    
    26.     '' now remove the duplicated items
    27.     ''
    28.     removeDuplicates x
    29.    
    30.     '' now display whats left
    31.     For i = 0 To UBound(x) - 1
    32.         Debug.Print i & ":" & x(i)
    33.     Next
    34. End Sub
    Last edited by plenderj; Apr 2nd, 2002 at 05:24 AM.
    Microsoft MVP : Visual Developer - Visual Basic [2004-2005]

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width