How to remove dupes from tables?

OK, what I’m trying to achieve is simple. I need to remove duplicate items in a table.

Example:

  • Input: {“banana”, “chicken”, 3, “banana”, 4, 3}
  • Output: {“banana”, “chicken”, 3, 4}

Note: this is a random example.

Any idea on how to make this happen??

2 Likes

Loop through it, add the values to a new array. Once a value on the new array is already there, it’s a duplicate.

1 Like

You could make a new table and add everything once.

local old_table = {"banana", "chicken", 3, "banana", 4, 3}
local new_table = {}

for i = 1, #old_table do
    local item = old_table[i]
    if not table.find(new_table, item) then
        table.insert(new_table, item)
    end
end

I’ve not actually tested this it’s just a concept.

2 Likes

Ok, sorry for making this topic just to figure it out.

local test = {1,2,4,2,3,4,2,3,4,"A", "B", "A"}

function RemoveTableDupes(tab)
	local hash = {}
	local res = {}
	for _,v in ipairs(tab) do
		if (not hash[v]) then
			res[#res+1] = v
			hash[v] = true
		end
	end
	return res
end

test = RemoveTableDupes(test)
print(test)

--[[Output:       [1] = 1,
                  [2] = 2,
                  [3] = 4,
                  [4] = 3,
                  [5] = "A",
                  [6] = "B"
]]

And yes, this would also work for my example

6 Likes

This code is very easy, so basically what we do is create a table with seen Numbers and a table with duplicate Numbers, so we loop through all the numbers and if the number that we’re on is not in the duplicate numbers that means there’s no duplicate and we add it to the seen numbers otherwise we add it to the duplicateNumbers, after that we print all the duplicate numbers (I added a table.conat to read it better)!

Code:

local numbers = {1, 2, 3, 3, 4, 5, 5}
local seenNumbers = {}

local duplicateNumbers = {}

for _, v in pairs(numbers) do
	if not table.find(seenNumbers, v) then
		table.insert(seenNumbers, v)
	else
		table.insert(duplicateNumbers, v)
		
	end
end

print(table.concat(duplicateNumbers, ", "))
2 Likes

Thanks for the reply! Although this problem has already been solved so there is no need to bump it. Thanks!

2 Likes

Np, I knew the problem was solved but I sent my code anyways xD

2 Likes