# Detect duplicates but not all duplicates

to explain theres a table

``````{a, a, b, b, c, c, c, d}
``````

and i want to only remove/detect any duplicate ‘c’ in the table and alter nothing else within the table
is that possible and if so how?

You could iterate over the entire array, skipping over c the first time it comes up and then remove all subsequent values of c.

I just wrote a quick implementation on how a function like that could be written.

``````local arr = {"a", "b", "c", "c", "c", "a"}

function removeDuplicates(array, filter)

local returnTable = table.clone(array) --Clone the table to prevent the function from making changes to the original one
local foundElement = false

for index = #returnTable, 1, -1 do --Iterate over the table backwards to prevent the forwards shift from table.remove() to mess up our index

if returnTable[index] ~= filter then --If the current element doesn't match the one we want to filer we skip to the next one
continue
end

if foundElement then --Remove elements we want to filter if we have already found the filtered element once
table.remove(returnTable, index)
continue
end

foundElement = true --If we haven't found the filtered element yet, set foundElement to true
end

return returnTable

end

print(removeDuplicates(arr, "c"))
--Prints {"a", "b", "c", "a"}
``````

As stated in the code the table is cloned to prevent the function from making changes to the original one. If you intend on updating your original table anyways you can rewrite the function to leave out the cloning step.

``````-- Function to find index of element in a table
local function findIndex(tbl, elem)
for i, v in ipairs(tbl) do
if v == elem then
return i
end
end
return nil
end

local table1 = {"a", "b", "c", "d"}

-- Find index of "c" in table1
local index = findIndex(table1, "c")

-- If "c" is found, remove it
if index then
table.remove(table1, index)
end
``````

check

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