1

I want to sorted table values from lowest to highest without changing keys value.

for ex.

tbl = {
    ['1'] = 3,
    ['2'] = 1,
    ['3'] = 2,
    ['4'] = 0
}

I need to get table data with keys as a value.

tbl = {
    ['1'] = 4,
    ['2'] = 2,
    ['3'] = 3,
    ['4'] = 1
}

I tried a lot of different solution but I coundn't find the good one.

Rapik
  • 11
  • 3
  • 1
    The two tables have exactly the same contents. – lhf Jan 31 '20 at 12:07
  • Yes, But It's only exemple. I create table dynamically, next I want to sort them from lowest value and at the end I'm going to insert firsts ten keys to other table. It's the reason why I have to keep keys values. Furthermore values for first table will be changing so to the second table will be added different keys. – Rapik Jan 31 '20 at 12:17
  • 1
    The first and second table are exactly the same, they're just written differently. – DarkWiiPlayer Jan 31 '20 at 13:11
  • Does this answer your question? [Associatively sorting a table by value in Lua](https://stackoverflow.com/questions/2038418/associatively-sorting-a-table-by-value-in-lua) – luther Jan 31 '20 at 13:25
  • Sorry there was a mistake. I edited the second table. – Rapik Jan 31 '20 at 14:11
  • It's hard to understand what you mean by 'sorted'. Generally that means an array-type table, one with a count of elements and elements in positions `1..n` (or `0..n-1`). By using strings for keys, you are abandoning that. It looks like you want to take a keyed table with strings and sort the keys by the value stored with that key in the table, then create another keyed table with the index of the key into that sorted array converted to a string as the key and the value as that original key converted to a number? If so, why? If not, can you give a better example? – Jason Goemaat Feb 10 '20 at 23:18
  • I got it. Thanks – Rapik Feb 13 '20 at 14:10

0 Answers0