Sorting a table in a table with an index

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve?
    Sort table, in table

  2. What is the issue?
    I don’t understand how to sort a table, in a table with an idnex

  3. What solutions have you tried so far?
    I tried to find similar posts, but there were simple tables like [“Test”] = 1, but I need [“Test”] = {“Hello”, 5}

My code:

local AliveTargets = {}
local character1 = workspace.character1
local character2 = workspace.character2
local character3 = workspace.character3

AliveTargets[character1.Name] = {character1, 5}
AliveTargets[character3.Name] = {character3, 8}
AliveTargets[character2.Name] = {character2, 3}

How can I sort by the second value so that it is like this
[character2] = {character2, 3}
[character1] = {character1, 5}
[character3] = {character3, 8}

1 Like

Depending on the size of your table, you could implement a simple sorting algorithm. I’m just going to demonstrate with selection sort, as it’s good for small data sets.

To implement selection sort in Roblox for a 2D table and sort it using the second value, you could do the following:

local tb = {
    {"a", 2}, 
    {"b", 1},
    {"c", 3}
}

for i = 1, #tb do
    local minIndex = i
    for j = i+1, #tb do
        if tb[j][2] < tb[minIndex][2] then
            minIndex = j
        end
    end

    tb[i], tb[minIndex] = tb[minIndex], tb[i]
end

Essentially, what this is doing is finding the index of the smallest value in the table and swapping it out with the value it is currently on until the outer loop reaches the last element. For a better explanation, refer to this video:

5 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.