Sorting alphabetically by last name if first and last name are in the same column

Sorting alphabetically by last name if first and last name are in the same column

schmolzpschmolzp Posts: 4Questions: 1Answers: 0
edited August 2012 in General
Is there an easy way to sort alphabetically by last name if first and last name are in the same column or would I have to use a hidden column? Thanks for any help you can provide.

Replies

  • allanallan Posts: 63,535Questions: 1Answers: 10,475 Site admin
    Yes indeed, a custom type based sorting plug-in could be created: http://datatables.net/development/sorting#type_based . Just split the work on ' ' and then sort on the second index.

    Allan
  • dotmundodotmundo Posts: 13Questions: 0Answers: 0
    edited September 2012
    This is how I got it to work. Note that I have a six column table with one column being hidden.

    [code]
    jQuery.fn.dataTableExt.oSort['full_name-asc'] = function(x,y) {
    var last_name_x = x.split(" ")[1];
    var last_name_y = y.split(" ")[1];
    return ((last_name_x < last_name_y) ? -1 : ((last_name_x > last_name_y) ? 1 : 0));
    };

    jQuery.fn.dataTableExt.oSort['full_name-desc'] = function(x,y) {
    var last_name_x = x.split(" ")[1];
    var last_name_y = y.split(" ")[1];
    return ((last_name_x < last_name_y) ? 1 : ((last_name_x > last_name_y) ? -1 : 0));
    };

    oTable = $('#tblPeople').dataTable({
    "iDisplayLength": NUM_DISPLAY_RECS,
    "sPaginationType": "full_numbers",
    "bProcessing": false,
    "bLengthChange": false,
    "bFilter": false,
    "sDom": 'tp',
    "aoColumns": [{"sType": "full_name"},
    {"sType": "string"},
    {"sType": "string"},
    {"sType": "string"},
    {"sType": "string"},
    {"sType": "string"}],
    });
    [/code]
  • dotmundodotmundo Posts: 13Questions: 0Answers: 0
    Ok I just found out the problem. That type definition and sort handler needed to be placed before the Datables declaration.

    Thanks
  • allanallan Posts: 63,535Questions: 1Answers: 10,475 Site admin
    If first name and last name are in different columns, the easiest way of doing this is to set the aDataSort option for the columns. That will let DataTables automatically do a multi-column sort.

    Allan
This discussion has been closed.