Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

Sorting a Table view

I don't see anything in the documentation or in the Kitchen Sink app that allows sorting for tables. Any ideas on how I would sort this? Ideally I want to pull some contact details and be able to sort by last name, birthday etc.

var win = Titanium.UI.currentWindow;

// build contacts table view
var contacts = [];

function getContacts()
{
    var data = [{title:'Add Contact'},{title:'Find Contact'},{title:'Find Contact Detail'}];
    contacts = Titanium.Contacts.getAllContacts();
    for (var i=0;i<contacts.length;i++)
    {
        var c = contacts[i]
        data.push({title:c.firstName + ' ' + c.lastName,hasChild:true});
    }
    return data;
};

var data = getContacts();

var tableview = Titanium.UI.createTableView({
    data:data,
});
— asked March 12th 2010 by nun dabold
  • contacts
  • sort
  • table
0 Comments

5 Answers

  • You would have to sort the JavaScript array at runtime - one method would be to use JavaScript sort.

    — answered March 12th 2010 by Kevin Whinnery
    permalink
    0 Comments
  • Thanks, I can make that work with a simple example like the one above but can't find the correct syntax when using the createTableViewRow. How do I refer to items within a row object?

    — answered March 12th 2010 by nun dabold
    permalink
    0 Comments
  • Never mind, I've got it now. I'll post some code shortly to help others.

    — answered March 12th 2010 by nun dabold
    permalink
    0 Comments
  • did you find the answer to this, I'm currently trying 'sort' but with no luck, says it's not a function of an array.

    — answered March 26th 2010 by Mark Walker
    permalink
    0 Comments
  • Hi Mark,

    Yes, I used the following code:

    
    data.sort(sortName);
    
    function sortName(thisObject,thatObject) {    
        if (thisObject.diff > thatObject.diff)
        {
            return 1;
        }
        else if (thisObject.diff < thatObject.diff)
        {
            return -1;
        }
        return 0;
      }
    

    "diff" is a property that I added to each row of the table, you can change that to refer to whichever property you wish to sort by.

    — answered March 26th 2010 by nun dabold
    permalink
    0 Comments
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.