Dictionary Value sorter seems to be duplicating entries

image

In our game we have a function to sort dictionary entries by time, however the pairs() function seems to be tripling the entries. This is the sort function in hand

local function DictionaySortByValue(t, v)
	--[[
	@PARAM - t - The table to get sorted
	@PARAM - v - the value name to find (MUST EXIST IN ALL ENTRIES)
	
	@OUTPUT - sortTable - sorted table of the original table
	
	Warning: this function will remove non-numeric keys
	]]
	
	--weird duplication issue wth
	
	local indexes = {}
	local toSort = {}
	local output = {}
	
	--go through each entry adding it to 'toSort' and pairing the original key to an index value
	for key, dictionary in pairs(t) do -- <-- most likely the issue
		local value = dictionary[v] -- fetch the original value
		--push the value to toSort and the key as the value as the key
		indexes[value] = key
		toSort[#toSort + 1] = value
	end
	
	--sort the table
	table.sort(toSort)
	
	--create the output table
	for _, vl in pairs(toSort) do
		local k = indexes[vl]
		local original = t[k]
		
		output[#output + 1] = original
	end
	
	return output
end

We have confirmed that it IS the function and not the thing being parsed into it

If you have a possible fix OR a better sorter to do the same operation without the duplication issue, it would be helpful

function SortTable(DictionaryTable)
	local array = {}
	for key, value in pairs(DictionaryTable) do
		array[#array+1] = {key = key, value = value}
	end
	table.sort(array, function(a, b)
		return a.value > b.value -- This sorts it Greatest to smallest, flip the operator if you want the other way around.
	end)
	return array
end

-- if you want to use this sorted table you can do the following:
local TableToSort = {["Andi"] = 5, ["Beans"] = 3}
local SortedTable = SortTable(TableToSort)

for i,v in pairs(SortedTable) do
    local indexkey = v.key
    local value = v.value
    print("The key is" .. indexkey , "The value is " .. value)
end

Fixed the issue, seems to be that it was not handling duplicate values correctly and was assinging everything to a single index

image

1 Like