Lua : remove duplicate elements

Prashant Gaur picture Prashant Gaur · Nov 19, 2013 · Viewed 13.3k times · Source

i am having a table in lua

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

I want to remove all duplicate elements in table.
Output should be

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

EDIT:

My try :

> items = {1,2,4,2,3,4,2,3,4,"A", "B", "A"}
> flags = {}
> for i=1,table.getn(items)  do
if not flags[items[i]] then
      io.write(' ' .. items[i])
      flags[items[i]] = true
   end
>> end
 1 2 4 3 A B>

It is working fine now. Thanks for answers and comments.

Answer

vogomatix picture vogomatix · Nov 19, 2013

Similar to example given by @Dimitry but only one loop

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

for _,v in ipairs(test) do
   if (not hash[v]) then
       res[#res+1] = v -- you could print here instead of saving to result table if you wanted
       hash[v] = true
   end

end