INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

Document Object Model (DOM)

Using JavaScript And DOM to Sort a Table by mwolf00
Posted: 19 May 03

Occasionally people ask how to sort a table using JavaScript.  The following code allows the user to sort a table regardless of the datatype (Date, number, or text).


<script>
var allNums = false;        // boolean variable to see if whole column is numeric
var allDates = false;        // boolean variable to see if column vals are all dates
var lastSort = -1;                // variable to hold last column number sorted
var absOrder = true;        // boolean to sort in reverse if on same column
//-----------------------------------------------------------------------
function setDataType(inValue) {
    // This function checks data type of a value
    //         - sets allNums to false if a non-number is found
    //        - sets allDates to false if a non-date is found
    var isDate = new Date(inValue);
    if (isDate == "NaN") {
        if (isNaN(inValue)){
            // The value is a string, make all characters in
            // String upper case to assure proper a-z sort
            inValue =  inValue.toUpperCase();
            allNums = false
            allDates = false
            return inValue;
          }
        else {
            // Value is a number, make sure it is not treated as a string
            allDates = false
            return parseFloat(1*inValue);
          }
        }
  else {
        // Value to sort is a date
        allNums = false
        return inValue ;
      }
  }
//-----------------------------------------------------------------------
function sortTable(col){
    if (lastSort == col){
        // sorting on same column twice = reverse sort order
        absOrder ? absOrder = false : absOrder = true
    }
    else{
        absOrder = true
    }
    lastSort = col
    allTR = document.getElementById("dataTable").childNodes[0].childNodes
    // allTR now holds all the rows in the dataTable
    totalRows = allTR.length
    colToSort = new Array()        //holds all the cells in the column to sort
    colArr = new Array()                //holds all the rows that correspond to the sort cell
    copyArr = new Array()            //holds an original copy of the sort data  to match to colArr
    resultArr = new Array()            //holds the output

    allNums = true
    allDates = true
    
    //store the original data
    //remember that the first row - [0] -  has column headings
    //so start with the second row - [1]
    //and load the contents of the cell into the array that will be sorted
    for (x=1; x < totalRows; x++){
        colToSort[x-1] = setDataType(allTR[x].childNodes[col].innerText)
        colArr[x-1] = allTR[x]
    }
    //make a copy of the original
    for (x=0; x<colToSort.length; x++){
        copyArr[x] = colToSort[x]
    }

    //sort the original data based on data type
    if (allNums){
        colToSort.sort(numberOrder)
    }
    else if (allDates){
        colToSort.sort(dateOrder)
    }
    else{
        colToSort.sort(textOrder)
    }

    //match copy to sorted
    for(x=0; x<colToSort.length; x++){
        for(y=0; y<copyArr.length; y++){
            if (colToSort[x] == copyArr[y]){
                boolListed = false
                //searcg the ouput array to make sure not to use duplicate rows
                for(z=0; z<resultArr.length; z++){
                    if (resultArr[z]==y){
                        boolListed = true
                        break;
                    }
                }
                if (!boolListed){
                    resultArr[x] = y
                    break;
                }
            }
        }
    }
    //now display the results - it is as simple as swapping rows
    for (x=0; x<resultArr.length; x++){
        allTR[x+1].swapNode(colArr[resultArr[x]])
    }
}
//-----------------------------------------------------------------------
function numberOrder(a,b){
    absOrder ? rVal = b - a : rVal = a - b
    return rVal
}
//-----------------------------------------------------------------------
function dateOrder(a,b){
    absOrder ? rVal = Date.parse(a) - Date.parse(b) : rVal = Date.parse(b) - Date.parse(a)
    return rVal
}
//-----------------------------------------------------------------------
function textOrder(a,b){
    if (a.toString() < b.toString()){
        absOrder ? rVal = -1 : rVal = 1
    }
    else{
        absOrder ? rVal = 1 : rVal = -1
    }
    return rVal
}
</script>

<table id="dataTable" border=1 cellspacing=0>
<tr>
    <th><a href="javascript: sortTable(0)">Data Field</a></th>
    <th><a href="javascript: sortTable(1)">Number Field</a></th>
    <th><a href="javascript: sortTable(2)">Date Field</a></th>
    <th><a href="javascript: sortTable(3)">Mixed Field</a></th>
</tr>
<tr>
    <td>Apples</td>
    <td>25</td>
    <td>1/2/2003</td>
    <td>200</td>
</tr>
<tr>
    <td>Grapes</td>
    <td>1003</td>
    <td>3/15/2002</td>
    <td>2/1/03</td>
</tr>
<tr>
    <td>Bananas</td>
    <td>03</td>
    <td>1/15/2001</td>
    <td>.2</td>
</tr>
<tr>
    <td>Cherries</td>
    <td>.579</td>
    <td>5/15/2003</td>
    <td>Alpha</td>
</tr>
<tr>
    <td>Donuts</td>
    <td>25</td>
    <td>5/15/2003</td>
    <td>10</td>
</tr>
</table>

Back to Javascript FAQ Index
Back to Javascript Forum

My Archive

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close