user2038438
user2038438

Reputation: 31

Reassign keys in an array to be in numerical order?

I'm looking for a way to reassign the keys in an array that looks like

table = {
    [1] = "value1",
    [5] = "value2",
    [12] = "value3",
    [27] = "value4"

}

To look like this

table = {
    [1] = "value1",
    [2] = "value2",
    [3] = "value3",
    [4] = "value4"

}

Upvotes: 1

Views: 68

Answers (1)

Paul Kulchenko
Paul Kulchenko

Reputation: 26794

Populate an array with your indexes first, then sort them, then replace the indexes with their values to get the result you need:

local t = {
  [1] = "value1",
  [5] = "value2",
  [12] = "value3",
  [27] = "value4"
}
local tupd = {}
for k in pairs(t) do table.insert(tupd, k) end -- populate
table.sort(tupd) -- sort
for k, v in ipairs(tupd) do tupd[k] = t[v] end -- replace

for k, v in ipairs(tupd) do print(k, v) end -- show

This should print what you expect.

(Not sure why the downvotes on your question as this looks like an interesting problem; although I have rarely seen this in practice; is this a homework? ;))

Upvotes: 2

Related Questions