Example:
table1 = {2,3,1}
table2 = {a,b,c}
to
table1 = {1,2,3}
table2 = {c,a,b}
This function does not modify either table, and returns the second table sorted according to the first. You can pass a comparison for keys in the first table, like in table.sort
.
local sort_relative = function(ref, t, cmp)
local n = #ref
assert(#t == n)
local r = {}
for i=1,n do r[i] = i end
if not cmp then cmp = function(a, b) return a < b end end
table.sort(r, function(a, b) return cmp(ref[a], ref[b]) end)
for i=1,n do r[i] = t[r[i]] end
return r
end
For instance:
local table1 = {2, 3, 1}
local table2 = {"a","b","c"}
local sorted = sort_relative(table1, table2)
print(table.unpack(sorted))
results in:
c a b
I would:
Step 1: Merge the two tables into pairs {{2,a},{3,b},{1,c}}
Step 2: Sort the pairs.
Step 3: Unmerge the resulting array.
table1 = {2,3,1}
table2 = {"a","b","c"}
-- Comparison function
function compare(x, y)
return x[1] < y[1]
end
-- Step 1: Merge in pairs
for i,v in ipairs(table1) do
table1[i] = {table1[i], table2[i]}
end
-- Step 2: Sort
table.sort(table1, compare)
-- Step 3: Unmerge pairs
for i, v in ipairs(table1) do
table1[i] = v[1]
table2[i] = v[2]
end
for i = 1,#table1 do
print(table1[i], table2[i])
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With