Erase repeated values

3

How could I do to delete repeated values in a table? Ex:

a = {1,2,3,4,3,2,1}

How would you erase 3, 2, and 1, keeping only one of each?

My table is one inside another:

a = {
{a=1, b=2},
{a=2, b=3},
{a=1, b=2},
}

In this case, the last value would be erased, since the a and the b of it and the first are equal. Pairs should be considered as a value for comparison purposes only. How to do this?

    
asked by anonymous 30.10.2014 / 17:06

2 answers

6

A more traditional approach to verifying duplicity as I had already done in another answer on C .

a = {{a=1, b=2}, {a=2, b=3}, {a=1, b=2}, {a=3, b=2}, {a=1, b=2}}

for i = #a, 2, -1 do
    for j = i - 1, 1, -1 do
        if (a[j].a == a[i].a and a[j].b == a[i].b) then
            table.remove(a, i)
            break
        end
    end
end

-- demonstração do resultado:
for i, j in pairs(a) do
    print(i .. ". a=" .. j.a .. ", b=" .. j.b)
end

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

    
30.10.2014 / 17:13
3

You can create other tables and use flags as flags to see if the element is already in the array or not. If your table has tables inside, just iterate through each table inside the first table:

local flags = {}
local a_filtrado = {}

for _, f in pairs(a) do
   for _,v in pairs(f) do
      if (not flags[v]) then
         a_filtrado[#a_filtrado+1] = v
         flags[v] = true
      end
   end

end

The a_filtrado table will have the elements only once.

    
30.10.2014 / 17:11