How to sort two tables simultaneously by using one of tables order?
Asked Answered
V

4

5

Example:

table1 = {2,3,1}
table2 = {a,b,c}

to

table1 = {1,2,3}
table2 = {c,a,b}
Velate answered 10/2, 2015 at 22:26 Comment(0)
L
6

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
Lipcombe answered 10/2, 2015 at 23:15 Comment(1)
This is an elegant and clean approach indeed. As the proverb goes, "there's more than one way to skin a cat".Weirdie
W
3

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
Weirdie answered 10/2, 2015 at 22:30 Comment(0)
W
1

I use key value pairs and the regular sort function to do the job:

table1 = {2,3,1}
table2 = {"a","b","c"}

table3 = {}    
for i, v in ipairs(table2) do
    table3[table1[i]] = v
end

table.sort(table1)

table2 = {}
for i = 1,#table1 do
    table2[i]=table3[table1[i]]
end
table3=nil

for i = 1,#table1 do
    print(table1[i], table2[i])
end
Weirdie answered 11/2, 2015 at 7:2 Comment(0)
O
0

Try this code, which uses the standard function table.sort:

table1 = {2,3,1}
table2 = {"a","b","c"}

table3 = {}
for i,v in ipairs(table1) do
    table3[table2[i]]=v
end

table.sort(table1, function (a,b)
    return table2[a] <= table2[b]
    end)

table.sort(table2, function (a,b)
    return table3[a] <= table3[b]
    end)

print("table1") 
for i,v in ipairs(table1) do
    print(i,v)
end

print("table2") 
for i,v in ipairs(table2) do
    print(i,v)
end
Odious answered 10/2, 2015 at 23:15 Comment(1)
Interesting approach but too costly.Weirdie

© 2022 - 2024 — McMap. All rights reserved.