Counting distinct values in an array

# Thread: Counting distinct values in an array

1. Member
Join Date
Dec 1969
Posts
67

## Counting distinct values in an array

I&#039;m struggling a bit with the VB script involved in counting distinct elements in array. Let&#039;s say I&#039;ve an array:<BR><BR>dim myarray(4)<BR>myarray(0)=3<BR>myarray(1)=6<BR>myar ray(2)=8<BR>myarray(3)=6<BR><BR>Now, len(myarray) returns a value of 4, but I&#039;d only like to count the distinct values - so the return should be 3. Any pointers would be greatly appreciated.

2. Senior Member
Join Date
Dec 1969
Posts
1,362

## RE: Counting distinct values in an array

Well, I don&#039;t have the time to dish out the code<BR><BR>but i would make a parallel array,<BR><BR>so loop through your array, if value doesn&#039;t match in parallel array, add to that array, then ubound your new array of originals.<BR><BR>hope this gets ya going.

3. Member
Join Date
Dec 1969
Posts
67

## RE: Counting distinct values in an array

Excellent! That was just the shove in the right direction I needed. The parallel array method works beautifully. Thanks for taking the time to help out :)<BR><BR>Jules

4. Senior Member
Join Date
Dec 1969
Posts
96,118

## Well, okay...for *small* arrays...

For truly large arrays, what you are describing becomes the equivalent of a bubble sort, with order n-squared performance. (Okay, technically it&#039;s n-squared even for tiny arrays, but n is so small that you don&#039;t care a lot.)<BR><BR>For larger arrays, a better scheme would be to use a *GOOD* sort algorithm to sort the array and then count by just checking adjacent values in the sorted array. Since a good sort algorithm could easily be an order of magnitude faster than n-squared...<BR><BR>Incidentally, if you check out the ASPFAQs, there&#039;s one in the Arrays section that shows how to sort an array by passing it to JavaScript and then using JS&#039;s built-in sort function. If you did that and then, instead of returning the sorted array, you did the counting in JS code, I&#039;d bet that it would be faster for all but the smallest arrays.<BR><BR>

5. Senior Member
Join Date
Dec 1969
Posts
1,362

## RE: Well, okay...for *small* arrays...

Leave it to you BW,<BR><BR>I am going to put a disclaimer under all of my code from now on.<BR>*probably not best way*<BR><BR>interesting idea. <BR>I would probably have just made a sql call instead of all that anyways. (i don&#039;t develop 1000 hit per minute sites though)

#### Posting Permissions

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