Search code examples
javascriptsortingalphabeticalalphabetical-sort

Javascript, sort columns by numbers or letters


I am trying to get different columns in a table to sort. I have them working for numbers but I don't know how to get it done for columns with alphabetical data.

Here is what I am working on: http://jsfiddle.net/nx4Ex/1/

Based on this: https://stackoverflow.com/a/7558600/2219915

I would have asked in a comment there but my rep is not high enough.

This is the script I am using. I know parsefloat deals with numbers but I'm not sure how I would change it to work with numbers and/or letters.

function sortTable(){
var tbl = document.getElementById("caltbl").tBodies[0];
var store = [];
for(var i=0, len=tbl.rows.length; i<len; i++){
    var row = tbl.rows[i];
    var column1 = parseFloat(row.cells[0].textContent || row.cells[0].innerText);
    if(!isNaN(column1)) store.push([column1, row]);
}
store.sort(function(x,y){
    return x[0] - y[0];
});
for(var i=0, len=store.length; i<len; i++){
    tbl.appendChild(store[i][1]);
}
store = null;
};

I also should mention that I am trying to avoid using any javascript libraries or plugins. All I need is this basic sorting functionality.


Solution

  • The sorting of table, build using plain JavaScript. I tested in chrome

    $('sort-date').addEventListener('click', function(){
        sortByDate( this );
    },false);
    
    $('sort-notify').addEventListener('click', function(){
        sortByNotify( this );
    },false);
    
    $('sort-id').addEventListener('click', function(){
        sortById( this );
    },false);   
    

    Clicking on column heading , sort the table contents . jsfiddle