Count specific values in array

Has anybody an example handy of how to count items in a 1-dim array?

stringArray(0) = “A”
stringArray(1) = “B”
stringArray(2) = “A”
stringArray(3) = “C”
stringArray(4) = “B”

etc.

I don’t know what values the array contains.

make temp dictionary for counts
loop through array.
Check if each item in dictionary. If yes, pick number, add one and put back. If no, put it in dictionary with 1.

on the end you have dictionary with counts.

dict.Lookup(s, 0) will return the previous count or 0 if it’s not found then adds 1 and stores that.

[code]Sub Action()
dim stringArray(4) As String
stringArray(0) = “A”
stringArray(1) = “B”
stringArray(2) = “A”
stringArray(3) = “C”
stringArray(4) = “B”

//scan stringArray into dictionary
dim dict As new Dictionary

dim s As String
for i As integer = 0 to stringArray.Ubound

s = stringArray(i)

dict.Value(s) = dict.Lookup(s, 0) + 1

next

//print dict content
dim keys() As Variant = dict.Keys
for i As integer = 0 to keys.Ubound
TextArea1.AppendText keys(i) + " " + dict.Value(keys(i)) + EndOfLine
next

End Sub

//result
A 2
B 2
C 1[/code]

note the alphabetical ordering of results is accidental, with a dictionary you can’t count on order.

[quote=127576:@Alexander van der Linden]Has anybody an example handy of how to count items in a 1-dim array?

stringArray(0) = “A”
stringArray(1) = “B”
stringArray(2) = “A”
stringArray(3) = “C”
stringArray(4) = “B”

etc.

I don’t know what values the array contains.[/quote]

What about Array.Ubound ?

Hi Michel…

no… I’m not interested in the length of the array; I’m interested how many unique values there are and how many of each…

Thanks

[quote=127582:@Will Shank]dict.Lookup(s, 0) will return the previous count or 0 if it’s not found then adds 1 and stores that.

[code]Sub Action()
dim stringArray(4) As String
stringArray(0) = “A”
stringArray(1) = “B”
stringArray(2) = “A”
stringArray(3) = “C”
stringArray(4) = “B”

//scan stringArray into dictionary
dim dict As new Dictionary

dim s As String
for i As integer = 0 to stringArray.Ubound

s = stringArray(i)

dict.Value(s) = dict.Lookup(s, 0) + 1

next

//print dict content
dim keys() As Variant = dict.Keys
for i As integer = 0 to keys.Ubound
TextArea1.AppendText keys(i) + " " + dict.Value(keys(i)) + EndOfLine
next

End Sub

//result
A 2
B 2
C 1[/code][/quote]
Works perfect!

Thanks