How to check if a chunk is overlapping another chunk in random terrain generation

I want a function that checks if there are 2 chunks overlapping each other and destroy one of them so it doesnt cause lag. Right now I have a random terrain generation thing and I made it able to load, and destroy chunks based off of a render distance. But whenever new chunks load, it overlaps the chunks that are alraedy loaded it which causes lots of lags and can slow down the loading process.
I have tried lots of different functions but none would work. The function I currently use is a function that is run in a while loop which also calls the functions that create and destroy the chunks, it basically just checks if there are chunks. It sort of works, but only on 1 chunk. When I test it myself, only 1 chunk is not being overlapped but I want it to do that with all of the chunks that are overlapped, not just one.

function existCheck()
	for _, v in pairs(map:GetDescendants()) do
		for _, code in pairs(map:GetDescendants()) do
			if v:FindFirstChild("Code").Value == code:FindFirstChild("Code").Value then
				v:Destroy()
				return true
			end
		end
	end
	return false
end

Each chunk has it’s own code. The code is the X position of it’s main part, multiplied but its Z position. And in that code, it is supposed to check if there are 2 chunk codes that are the same. I did some checking and I saw that each chunk has their own code and the chunks that overlap have duplicate codes which this function is supposed to identify then destroy.

You have a return in the loop, which stops your function after the first overlapping chunk is destroyed.

I removed the return and edited the code but now it deletes all the chunks that are created. I believe there is a problem in me detecting if there are 2 chunks with the same id. How would I go about to check if there are 2 chunks with the same ID? I also made a similar function but instead it printed out which would be duplicates with a given table that counted 1,2,3,4,5 and it said all of them were duplicated so my way of checking is wrong and I don’t know how to check if there are 2 chunks with the same ID.

Try adding v ~= code to your if statement. Another option is removing code with table.remove when you destroy v.

This was my updated code. It works, but not the correct way. It deletes all the chunks, when I only want to delete chunks with duplicated ID values. image

I managed to create a fix, and now it works. However, upon detecting the overlapping chunk, it deletes both the chunks. I want it to only delete the overlapping one, not both of them. Other than that, it works fine