How to find the intersection of two tarrays ?

Hello. How to find the intersection of two TArray?

Suppose there are two tarrays:
TArray Array1 = TArray{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
TArray Array2 = TArray{1, 5, 8};
TArray IntersectionArray;

How to get the intersection of two arrays and write the result to IntersectionArray ?
For example: exclude the elements of the Array2 from Array1 and get the result into the IntersectionArray array.

.h

UFUNCTION(BlueprintCallable)
TArray<int32> Intersect(const TArray<int32> A, const TArray<int32> B);

.cpp

TArray<int32> AMyActor::Intersect(const TArray<int32> A, const TArray<int32> B)
{
	TArray<int32> Output;
	for (int i = 0; i < B.Num(); ++i) {
		if (A.Contains(B[i])) {
			Output.Add(B[i]);
		}
	}
	return Output;
}

Edit added const to make sure the arrays remain unchanged.
Could also be made a static function in a blueprint function library.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.