Delete repeated values

Asked

Viewed 190 times

3

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

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

How would you delete 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 that case, the last value would be deleted, since the a and the b of it and of the first are equal. Pairs should be considered as a value only for comparison purposes. How to do this?

2 answers

6


A more traditional approach to verify 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

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

3

You can create other tables and use as "signal" variables (flags) to see if the element is already in the array. If your table has tables inside, just iterate for 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 table a_filtrado will have the elements a single time.

  • 1

    It would have as a functional example in the IDEONE? I couldn’t get your code running as it is.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.