Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Is there a way of removing duplicates inside a table?

Asked by 6 years ago

Is there any way or method to remove all duplicate numbers or strings from a table? My script inserts textbuttons with numbers pulled from a table into a gui, but due the duplicates some of the buttons have the same text.

1 answer

Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

Hi Kip,

You can simply solve this by going through the table and adding each value to another table and then check if that table contains the value that your loop is looping through. Here, I'll show you a simple example down below:

local tab_with_values = {1, 3, 4, "Whatever", "AnyValue", "Any Value", 3};
local new_tab = {};

for _, value in next, tab_with_values do
    if not new_tab[value] then
        new_tab[value] = true;
    end
end

However, using this method, you have to be aware of how the values are stored in the new_tab. The values become the indexes and you can't use a for loop to access them like before, you can only use a for each iteration since for loops only work with tables that have integer indexes. However, these have a wide variety of indexes other than integers, I assume. So, this is how you would access each value inside.

-- When you know the value you're looking for

local val_i_want = "AnyValue";

local val_u_want = new_tab[val_i_want]; -- This will index the value and return the exact value for you.

-- When you need to loop through the table and maybe don't know the value or want to just change all values inside of the table.

for value, _ in next, new_tab do
    print(value) -- This is the value, since the value has exchanged places with the index, like I discussed before.
end

Well, I hope I helped and have a nice day/night.

Thanks,

Best regards,

~~ KingLoneCat

Ad

Answer this question