user6546633
user6546633

Reputation:

How to sort a table according to another ordered table?

I have a specific table with natural numerical key and string value like this {"192", "127", "114", "186"}, it can be named ordered table, and there is a another table is a subset of ordered table but out of order, such as {"114", "192"}. How can I sort the latter one according to the ordered table???

Upvotes: 2

Views: 56

Answers (1)

hugomg
hugomg

Reputation: 69934

One thing you can do is create a helper table that maps a string to its position in the "ordered table". This allows you to quickly see, given two strings, which should appear before the other.

Then, you can use this helper table to implement a comparison function for your sort. In Lua, the table.sort has an optional parameter that is a custom comparison function. This comparison function should accept a pair of values from the table (s1 and s2) and should return true if s1 < s2 according to your desired ordering.

ordered_table = {"192", "127", "114", "186"}

indexes = {}
for i, s in ipairs(ordered_table) do
  indexes[s] = i
end

unordered_table = {"114", "192"}
table.sort(unordered_table, function(s1, s2)
  local i1 = assert(indexes[s1])
  local i2 = assert(indexes[s2])
  return i1 < i2
end)

Upvotes: 2

Related Questions