12

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.

Dmitry Ledentsov
  • 3,620
  • 18
  • 28
Prashant Gaur
  • 9,540
  • 10
  • 49
  • 71
  • note that none of the answers thus far posted handle the case of duplicate elements which are themselves also tables, as that also requires a satisfactory answer to [how to compare tables](https://stackoverflow.com/questions/20325332/how-to-check-if-two-tablesobjects-have-the-same-value-in-lua) – TamaMcGlinn Nov 11 '22 at 10:52

4 Answers4

27

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
vogomatix
  • 4,856
  • 2
  • 23
  • 46
4
local test = {1,2,4,2,3,4,2,3,4,"A", "B", "A"}

-- make unique keys
local hash = {}
for _,v in ipairs(test) do
    hash[v] = true
end

-- transform keys back into values
local res = {}
for k,_ in pairs(hash) do
    res[#res+1] = k
end

-- 1 2 3 4 A B
for _,v in ipairs(res) do
    print(v)
end

test = res

... a simple, straightforward solution just from the head, but I think, the hint is given in the PiL book

what have you tried to solve the problem?

Dmitry Ledentsov
  • 3,620
  • 18
  • 28
3
local xx = {'a','b','c','d','a','d','f','g','a'}
table.sort(xx)
local result = {}

for key,value in ipairs(xx) do
  if value ~=xx[key+1] then
    table.insert(result,value)
  end
end

for key,value in ipairs(result) do
  print(key,value)   
end
nonchip
  • 1,084
  • 1
  • 18
  • 36
  • 1
    Usually, even if this code answers the question, it is recommended to briefly explain what it does and why it is the right answer. – Edson Menegatti Dec 16 '18 at 21:37
0
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

Output -

1 2 4 3 A B>
Prashant Gaur
  • 9,540
  • 10
  • 49
  • 71