Compare Two Arrays

December 26, 2007 – 4:14 pm

For one of my projects I needed a function to compare two arrays. The following function returns true if both array have the same elements (regardless of their position in arrays).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Function ArraysAreEqual (vA As Variant, vB As Variant) As Variant
 
	Dim IsEqual As Variant
	ArraysAreEqual = True
 
	Forall a In vA
		IsEqual = False
		Forall b In vB
			If a = b Then
				IsEqual = True
				Exit Forall
			End If
		End Forall
		If Not IsEqual Then
			ArraysAreEqual = False
			Exit Function
		End If
	End Forall
 
	Forall b In vB
		IsEqual = False
		Forall a In vA
			If b = a Then
				IsEqual = True
				Exit Forall
			End If
		End Forall
		If Not IsEqual Then
			ArraysAreEqual = False
			Exit Function
		End If
	End Forall
 
End Function

To execute your code only when both array are different simply use

1
2
3
4
5
	If Not (ArraysAreEqual ( mBefore, mAfter )) Then
	   ' your code goes here
           ' ...
 
	End If

Related posts:

  1. Get View Column Sums With LotusScript
  2. Programmatically Check If Export Of View Data Is Disabled
  3. Is User A Member Of A (Nested) Group ?
  4. Excel Report Class
  5. How to use a list to get around the Array size limit

  1. 5 Responses to “Compare Two Arrays”

  2. Thanks for sharing your code.
    I just wonder if there is any particular reason to define the return variable as variant. I would suggest using integer or boolean instead. Is that for the sake of backward compatibility or is there any other reason?

    By Mirek Navratil on Dec 29, 2007

  3. Function ArraysAreEqual (vA As Variant, vB As Variant) As Variant

    Dim rez As Variant
    rez = Evaluate({@implode(@sort(@Explode(“} & Join(vA, “~”) & Join(vB, “~”) )

    if rez(0) = 0 then ArraysAreEqual = false else ArraysAreEqual = true

    end function

    By Dmytro on Jan 8, 2008

  4. try my code, my approach more interesting, on my opinion :)
    the idea is simple, we sort our arrays and convert them to string, then we will compare two string and will get the result.

    advantage of my approach:
    - more simple, just 1 line;
    - faster;
    - we can compare any number of arrays

    By Dmytro on Jan 8, 2008

  5. Dmytro, thanks for sharing.

    By eknori on Jan 8, 2008

  6. Hi
    This formula is not working… even brackets for @sort and all missed.

    By Tamilselvi on Feb 17, 2010

Post a Comment