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)
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.
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