Jump to content

Table sorting


klaw

Recommended Posts

Okay I have a couple questions regarding table sorting:
 

How can I sort this table, from A to Z by it's first value, so myTable[1]?

local myTable = {
  { "David", 21, "Male", "Chicago" },
  { "Jessica", 42, "Female", "New York" },
  { "Kevin", 14, "Male", "New York" },
  { "Louise", 21, "Female", "Washington" }, 
}

 

Similar with numbers, how do I sort that table from lowest to highest by it's second value, myTable[2]?

 

Thank you.

 

  • Like 1
Link to comment

Here's some examples:

-- sort by first value in table
table.sort(myTable,function(a,b) return a[1] < b[1] end)

-- sort by second value in table
table.sort(myTable,function(a,b) return a[2] < b[2] end)

-- sort by named key value in table (if there's any)
table.sort(myTable,function(a,b) return a.name < b.name end)

Use the last one if you're doing something like this:

{name = "David", age = "21"}

Hope this helps.

  • Like 2
Link to comment

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...