Sort a table a certain way

How would you sort Table2 to be like Table1?

local Table1 = {1,3,4,2,5}
local Table2 = {5,4,3,2,1} 

Change Table2 to {1, 3, 4, 2, 5}?
1 Like

You would use table.sort() to achieve this.

I dont understand the use of this, those numbers are keys? or are values?

Specifically for the tables you are showing… you could do something like this:

local Table1 = {1, 3, 4, 2, 5}
local Table2 = {5, 4, 3, 2, 1}

local tempTable = {}
for i, v in ipairs(Table1) do
	tempTable[v] = i
end

table.sort(Table2, function(a, b)
	return tempTable[a] < tempTable[b]
end)

warn(Table2)


This is the output of table2:

{
    [1] = 1,
    [2] = 3,
    [3] = 4,
    [4] = 2,
    [5] = 5
}
2 Likes

They don’t want the elements to be sorted(according to what they posted as examples) and you also don’t provide any further information about how they’re going to use table.sort.

You can just search ever other thread regarding the same question or look at the example @Dev_Peashie has displayed above.

1 Like

The only use case I see for this is checking if 2 tables are equal(in the sense that they have the exact same elements or no) however even that won’t work if you try to directly compare the 2 tables(by doing Table1 == Table2) so I thought to write you a simple function for it:

local Table1 = {1,3,4,2,5}
local Table2 = {5,4,3,2,1}

--Receives two tables t1, t2 as input and returns if they have the same elements
function HaveSameElements(t1: {any}, t2: {any}): boolean
	--This line of code ensures we always copy the table with the least amount of elements
	if #t1 < #t2 then t1, t2 = t2, t1 end
	--Creates a copy of t2 so we don't accidently damage the data in the real table
	local t2Copy = {} 
	for i, v in pairs(t2) do t2Copy[i] = v end
	--Loops through all elements of t1
	for i, v in pairs(t1) do 
		--Searches for the first occurance in t2
		local index = table.find(t2Copy, v)
		--If it doesn't find one, the tables are not equal
		if not index then return false end 
		--If it does it removes it from t2
		table.remove(t2Copy, index)
	end
	--If t2 has no elements left, the tables are equal, else they aren't
	return (#t2Copy == 0)
end

print(HaveSameElements(Table1, Table2)) --true 

Note: this only works for arrays, not dictionaries

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