Jump to content

table sort


klaw

Recommended Posts

Posted

I have a table:

local myTable = {
  	[204] = { 50, 10 },
  	[820] = { 22, 32 },
  	[103] = { 42, 66 },
  }

How can I sort this table by the first index, so it'd be in order, like: 50, 42, 22 descending.

  • Forum Administrators
Posted
table.sort(myTable, function(a, b) return a[1] > b[1] end)

I think...

  • Moderators
Posted (edited)

You can't order this table since it is already ordered.

local myTable = {
      [204] = { 50, 10 },
      [820] = { 22, 32 },
      [103] = { 42, 66 },
  }


Will look like this:

local myTable = {

      [103] = { 42, 66 },
      [204] = { 50, 10 },
      [820] = { 22, 32 },    
  }

 

If you want to order this table, you need a different format were there are no custom indexes.

Edited by IIYAMA
Posted (edited)

You don't have to change your table format (at least it depends on what you're doing and how your script is functioning).

Check this old post of mine for an easy solution:

 

Edited by Tails
  • Moderators
Posted

lol, you are changing the table format of the copy.

Then you can better use two linked tables, saves you a lot of performance.

Posted (edited)
2 hours ago, IIYAMA said:

lol, you are changing the table format of the copy.

Then you can better use two linked tables, saves you a lot of performance.

This is a perfectly normal way of doing it. Sometimes you want to take some data from an existing table into a new one and use that for sorting without messing with the original. But go ahead and post your solution here, OP needs it.

Edited by Tails
  • Moderators
Posted
local myTable = {
	{103, 42, 66 },
	{204, 50, 10 },
	{820, 22, 32 }
}

local myTableNewFormat = {
--[[
	[103] = {103, 42, 66 }, -- shared/linked with myTable 
	[204] = {204, 50, 10 },
	[820] = {820, 22, 32 }
]]
}

for i=1,#myTable do
	myTableNewFormat[myTable[i][1]] = myTable[i]
end

As you know tables are objects and they can exist at multiple places at the same time. Which means that myTable and myTableNewFormat contains exactly the same data, but with different indexes.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...