x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 257

# create a common array

Hi,

I have 2 arrays : arr1(5) , arr2(3) . How can I create a third array which contains only the common items in arr1 & arr2
Important: arr2() may becomes one time longer than arr1() , I mean that their long are not fixed
I look forward the code which can do that.

Thanx
0
ray14
• 2
1 Solution

Commented:
Are the array's sorted in any particular order?
0

Commented:
' Form1 code
Option Explicit

Private Sub Form_Click()
Print Join(GetCommon(Split("a b cc dd", " "), Split("cc dd e f", " ")), " ")
End Sub

' returns items which are in a1 and a2
Private Function GetCommon(a1 As Variant, a2 As Variant) As Variant
Dim col1 As New Collection, colBoth As New Collection, arrBoth() As String
Dim i As Long, tmp As String
On Error Resume Next

' build collection of unique values
For i = 0 To UBound(a1)
col1.Add a1(i), "k" & a1(i)
Next

' test all values in a2
For i = 0 To UBound(a2)
Err.Clear
tmp = col1.Item("k" & a2(i)) ' if Item does not exist, we'll get error
If (Err = 0) Then colBoth.Add a2(i), "k" & a2(i) 'Item exists
Next

' fill array
ReDim arrBoth(0 To colBoth.Count - 1)
For i = 1 To colBoth.Count
arrBoth(i - 1) = colBoth.Item(i)
Next
GetCommon = arrBoth    ' return array
End Function
0

Author Commented:
Hi ameba,

Thanks for your answer and it is  nice to receive your help again. As I promised in my last question I’ll increase the points by +50 then it will be 100  thanks again.

Ray14
0

Commented:
Thank you  :-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

## Featured Post

• 2
Tackle projects and never again get stuck behind a technical roadblock.