Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Compare two arrays and return matches 2

Status
Not open for further replies.

billbose

Programmer
Jan 15, 2001
66
US
I have these two arrays. I want to compare them and return the matches

firstArr = Array("John", "Jacob", "Sam", "Bill")

secondArr = Array("Jen", "Bill", "Mike", "Steve", "John")


Here the match would be "John" and "Bill". But how I do it in Vbscript?
 
Hello billbose,

Brut force is this for arrays of string elements. Operation's leading order is nXm with m, n the dimension of the arrays.
Code:
firstArr = Array("John", "Jacob", "Sam", "Bill")
secondArr = Array("Jen", "Bill", "Mike", "Steve", "John")
dim matchArr()
for i=0 to ubound(firstArr)
    for j=0 to ubound(secondArr)
        if strComp(firstArr(i), secondArr(j), 1)=0 then
           on error resume next
            redim preserve matchArr(ubound(matchArr)+1)
            if err.number<>0 then redim matchArr(0) : err.clear
            on error goto 0
            matchArr(ubound(matchArr))=firstArr(i)
        end if
    next
next
on error resume next
wscript.echo "The number of matches is " & ubound(matchArr)+1
if err.number<>0 then wscript.echo "No match is reported." : err.clear
on error goto 0
'etc etc other stuff
regards - tsuji
 
Another way:
firstArr = Array("John", "Jacob", "Sam", "Bill")
secondArr = Array("Jen", "Bill", "Mike", "Steve", "John")
tst = Chr(1) & Join(secondArr, Chr(1)) & Chr(1)
res=""
For i = 0 To UBound(firstArr)
If InStr(1, tst, Chr(1) & firstArr(i) & Chr(1), 1) > 0 Then
res = res & firstArr(i) & vbCrLf
End If
Next
If Len(res) > 0 Then MsgBox res

Hope This Help, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Thank you tsuji and PHV for your codes. They were quite helpful.

regards,
billbose
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top