Move table elements

How can I make the elements of the Table swap positions?

--[[
ItemMoveUp("world"):
    In -> {
        "Hello",
        "world",
        "Nice"
    }

    Out -> {
        "world",
        "Hello",
        "Nice"
    }

ItemMoveDown("Hello"):
    In -> {
        "Hello",
        "world",
        "Nice"
    }

    Out -> {
        "world",
        "Hello",
        "Nice"
    }
]]--

How can I achieve this?

I’ve created a simple function to help with your problem.:

The “newPosition” argument is where the element’s new position would be in the table relative to it’s current position in the table

local function ItemMove(Table:{}, Item:any, newPosition:number)
	local Index
	Index = table.find(Table, Item)
	
	if not Index then return end
        local Value = Table[Index]
	local newIndex = math.max(Index+newPosition, 1)
	
	table.remove(Table, Index)
	table.insert(Table, newIndex, Value)
end

Testing the function:




Edit: @wsyong11 I used table.find to get the element’s current index whichone assume to be more efficient than my implementation since it was implement by Roblox

3 Likes

Thank you very much!
30 worldsssssss

1 Like

You’re welcome


1 Like
local function reverseTable(t : {}) : ({}) -> ({})
	local r : {} = table.create(#t)
	for i : number = #t, 1, -1 do
		 table.insert(r, t[i])
	end
	return r
end

That seems like a useful function on it’s own but if you read the post carefully, they’re trying to move an element in the table to a new position relative to where the element’s current position is

local function moveTable(t : {}, i : number, j : number) : ({}, number, number) -> ()
	local v : any = table.remove(t, i)
	table.insert(t, j, v)
end
local t = {"a", "b", "c"}
moveTable(t, 1, 3)
print(t[3]) --a
2 Likes

That works too but they’re trying to just call the function which the element. However, your reply has prompted me to use table.find instead in my code so I will make changes to my original solution