# Array difference

## Recommended Posts

If I have two arrays

Dim \$aArrayA[10] = [1, 2, 3, 4, 5, 12, 13, 37, 74, 115]

Dim \$aArrayB[10] = [10, 12, 3, 74, 45, 7, 11, 13, 14, 15]

I want to obtain the difference between them.

eg obtain the output

\$aDifference = [1, 2, 4, 5, 37, 115]

I guess that I can do it with nested loops, but is there a snazzy way ie a function that returns this.

Thanks,

Antionmy

PS. I am this is for my first AutoIt script, so please forgive me if this has been answered already, but I have not been able to find it via search.

##### Share on other sites

loops are the only way i know of.

```func substract2arrays(\$aArrayA,\$aArrayB)
If(ubound(\$aArrayA)=ubound(\$aArrayB) AND IsArray(\$aArrayA) AND IsArray(\$aArrayB) Then

for i=0 to ubound(\$aArrayA) step 1
Next
Else
Return @error
Endif
Endfunc```

this should be the way to go

##### Share on other sites

If I have two arrays

Dim \$aArrayA[10] = [1, 2, 3, 4, 5, 12, 13, 37, 74, 115]

Dim \$aArrayB[10] = [10, 12, 3, 74, 45, 7, 11, 13, 14, 15]

I want to obtain the difference between them.

eg obtain the output

\$aDifference = [1, 2, 4, 5, 37, 115]

I guess that I can do it with nested loops, but is there a snazzy way ie a function that returns this.

Thanks,

Antionmy

PS. I am this is for my first AutoIt script, so please forgive me if this has been answered already, but I have not been able to find it via search.

This requires two nested loops. You want to loop through each item in A with the outer loop, testing it against each item in B with the inner loop. If there is a match, delete the item from A. Note that the loop move backwards through A to avoid subscript out of range errors:
```#include <Array.au3>

Global \$aArrayA[10] = [1, 2, 3, 4, 5, 12, 13, 37, 74, 115]
Global \$aArrayB[10] = [10, 12, 3, 74, 45, 7, 11, 13, 14, 15]

For \$a = UBound(\$aArrayA) - 1 To 0 Step -1
For \$b = 0 To UBound(\$aArrayB) - 1
If \$aArrayA[\$a] = \$aArrayB[\$b] Then
_ArrayDelete(\$aArrayA, \$a)
ExitLoop
EndIf
Next
Next

_ArrayDisplay(\$aArrayA, "Result")```

Valuater's AutoIt 1-2-3, Class... Is now in Session!For those who want somebody to write the script for them: RentACoder"Any technology distinguishable from magic is insufficiently advanced." -- Geek's corollary to Clarke's law

## Create an account

Register a new account

×

• Wiki

• Back

• Git