# Detecting a duplicate variable

I’ll keep this short.

Let’s say you have a table with variables:

``````local t = {"a","a","b","c")
``````

Is there a way to detect if there’s two or more identical variables, and then remove them? In this example, there’s 2 `a` variables in this table.

If you have any suggestions or solutions, please comment them down below. Thank you.

1 Like
``````local function ClearDuplicates(t: {any})
local Auxiliary = {}
for _, v in t do
Auxiliary[v] = true
end
table.clear(t)
for v in Auxiliary do
table.insert(t, v)
end
end

local d = {"a", "a", "b", "c", "b", "d", "x", "y", "z", "z"}

ClearDuplicates(d)

print(d)
``````
3 Likes

You could use table.find to search for the same value and check its not the same index you’re checking from. For example

``````local function detectDuplicate(t, index)
local value = t[index]
local resultIndex = table.find(t, value)
if resultIndex == index then
local resultIndex = table.find(t, value, index+1)
if resultIndex then
return resultIndex
end
else
return resultIndex
end
end

local t = {"a","a","b","c")

detectDuplicate(t, 1) -- 2 (put the index of the value you wanna search)
detectDuplicate(t, 2) -- 1
``````

doesn’t work with dictionaries btw.

Also this only detects one other duplicate and returns the index of that duplicate, so you would have to repeat the function until it returns nil if you wanna remove all duplicates.

1 Like

You have to insert the index though, I want it to search through all variables and then see which ones are identical to another.

Uh if you want to remove duplicates entirely you could probably use @overflowed 's solution otherwise mine is just for checking lol.

This function will just return an array of index with duplicate values. (It doesn’t count the first instance of a value as a duplicate ofc)

``````local function getDuplicateTable(t)
local duplicateTable = {} -- table full of duplicates
for index, value in t do
if table.find(duplicateTable, index) then continue end
local resultIndex = table.find(t, value)
while resultIndex do
if resultIndex ~= index then
table.insert(duplicateTable, resultIndex)
end
resultIndex = table.find(t, value, resultIndex+1)
end
end
return duplicateTable
end

local t = {"a","a","b","c", "c"}
local duplicateTable = getDuplicateTable(t)
print('{'..table.concat(duplicateTable, ', ')..'}') -- {2, 5}

-- removing the duplicates
for _, i in duplicateTable do
t[i] = nil
end
``````

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