Advertisement
lalatino

Sorting Table in Javascript

Jul 9th, 2012
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
  3. <head>
  4. <title> http://stackoverflow.com/questions/11400250/javascript-sort-rows-by-column </title>
  5.  
  6. <style type="text/css">
  7. table {
  8.     width:100%;
  9.     border:1px solid #ccc;
  10. }
  11.  
  12. table thead th {
  13.     background-color: #eee;
  14.     text-align: left;
  15.     cursor:pointer;
  16. }
  17.  
  18. </style>
  19.  
  20. <script type="text/javascript">/* <![CDATA[ */
  21.  
  22. // global variables for sorting functions
  23. var x; // array of objects { 'cell value in the sorted column', 'reference to ith table row'}
  24. var length; // count of table rows
  25. var dir; // sort direction
  26. var col=-1; // sorted column
  27.  
  28. /////////////////////////////////////////////////////////
  29. // parameters:
  30. // column number == 0 | 1 | 2 ....
  31. // sorted type == "string" | "integer" | "float"
  32. // direction  ==  0 | 1 ~ descending or ascending
  33. // sort algorythm ==  "bubblesort" | "quicksort"
  34. /////////////////////////////////////////////////////////
  35. function sortBy(column_number, sorted_type, direction, algorythm)
  36. {
  37.     // SET VARIABLES
  38.     var table_elements = document.getElementsByClassName("summary_table");
  39.     var table_element = table_elements[0].tBodies[0];
  40.     var table_rows = table_element.rows;
  41.     length=table_rows.length;
  42.     dir = (col==column_number)? (dir?0:1) :direction; // set user friendly sort direction
  43.     col = column_number;
  44.     //var start = new Date().getTime();//time measure starts
  45.    
  46.     // INITIALIZE ARRAY
  47.     x = new Array();
  48.     for (var i=0; i<length; i++) { //getting values in the column column_number
  49.         x[i] = new Object();
  50.         x[i].row = table_rows[i]; // references to table rows
  51.         //x[i].value = table_rows[i].cells[col].innerHTML; //value on the row i
  52.         x[i].value = getCellText(table_rows[i].cells[col]); //value on the row i
  53.         x[i].value = x[i].value.replace(/^\s*/g,''); //remove whitespaces alias ltrim (optional)
  54.         // if sorted_type=="string" then no change;
  55.         if (sorted_type=='integer') x[i].value = parseInt(x[i].value,10);
  56.         if (sorted_type=='float') x[i].value = parseFloat(x[i].value);
  57.         //x[i].value = x[i].value.toLowerCase(); // MAKE SEARCHING CASE INSENSITIVE
  58.     }
  59.     //alert('var x == '+x.toSource());
  60.    
  61.     // SORT ARRAYS
  62.     if (algorythm == 'bubblesort') { bubbleSort(); }
  63.     else if (algorythm == 'quicksort') { quickSort(0,length-1); }
  64.     else { alert('Unsupported sorting algorythm specified, table will be not sorted. '); return; }
  65.    
  66.     // UPDATING THE TABLE
  67.     //alert('Updating the table. ' + table_element + x.toSource());
  68.    
  69.     // METHOD 1 - very fast
  70.     var n=document.createElement('tbody'); //here will be faster appending
  71.     for (var i=0; i<length; i++) {
  72.         var r=x[i].row.cloneNode(true);
  73.         n.appendChild(r);
  74.     }
  75.     table_element.parentNode.replaceChild(n,table_element);
  76.     //alert('New table body length is ' + n.rows.length); //test ok
  77.    
  78.     // METHOD 2 - very slow
  79.     /*
  80.     table_element.innerHTML='';
  81.     for (var i=0; i<length; i++) {
  82.         table_element.appendChild(x[i].row); //this appending is much slower
  83.     }
  84.     */
  85.    
  86.     //var end = new Date().getTime();//time measure ends
  87.     //alert('row sorting time + table update time = '+(end-start));
  88.     //return (end-start); //return execution time
  89. }
  90.  
  91.  /////////////////////////////////////////////////////////
  92.  // getCellText - recursive obtaining text from the <td> element
  93.  // thanks to Stuart Langridge, who has originally programmed this function
  94.  // http://www.kryogenix.org/code/browser/sorttable/
  95. /////////////////////////////////////////////////////////
  96. function getCellText(el) {
  97.     var str = '';
  98.     var cs = el.childNodes;
  99.     var l = cs.length;
  100.     for (var i = 0; i < l; i++) {
  101.         if (cs[i].nodeType==1) { //ELEMENT_NODE
  102.             /*    if (cs[i].nodeName=='INPUT' && cs[i].attributes.getNamedItem('type') && cs[i].attributes.getNamedItem('type').value=='text') //html form inputbox
  103.                 return cs[i].value ? cs[i].value:'';
  104.                 else
  105.             */     str += getCellText(cs[i]); // div, p, a...
  106.         }
  107.         else if (cs[i].nodeType==3) {//TEXT_NODE
  108.             str += cs[i].nodeValue;
  109.         }
  110.         return str;
  111.     }
  112. }
  113.  
  114.  /////////////////////////////////////////////////////////
  115.  // Bubblesort - sufficient for short tables
  116.  /////////////////////////////////////////////////////////
  117. function bubbleSort() {
  118.     var ri,rj,tmp;
  119.     for (var i=0; i<length; i++) {
  120.         ri=x[i].value;
  121.         for (var j=i+1; j<length; j++) {
  122.             rj=x[j].value;
  123.             if ((dir==0 && rj<ri) //compare values upward (for dir==0)
  124.              || (dir==1 && rj>ri)) //compare values downward (for dir==1)
  125.             {
  126.                 //alert(this.method+' swapping rows '+ri+' + '+rj);
  127.                 tmp=x[i].value;//swapping row values
  128.                 x[i].value=x[j].value;
  129.                 x[j].value=tmp;
  130.                 tmp=x[i].row;//swapping row references
  131.                 x[i].row=x[j].row;
  132.                 x[j].row=tmp;
  133.                 ri=rj;//updating ri variable for this pass
  134.             }
  135.         }
  136.     }
  137. }
  138.  
  139.  /////////////////////////////////////////////////////////
  140.  // Quicksort - highly recommended for long tables
  141.  /////////////////////////////////////////////////////////
  142. function quickSort(L,R) {
  143.     var i,j,xp,tmp;
  144.     i=L; j=R;
  145.     xp=x[Math.floor((L+R)/2)].value; /* pivot taken from the middle of unsorted array */
  146.     do {
  147.         if(dir) { //descending sort
  148.             while((x[i].value>xp)&&(i<R)) i++;
  149.             while((x[j].value<xp)&&(j>L)) j--;
  150.         }
  151.         else { //ascending sort
  152.             while((x[i].value<xp)&&(i<R)) i++;
  153.             while((x[j].value>xp)&&(j>L)) j--;
  154.         }
  155.         if(i<=j) {
  156.             //alert('swapping row values '+x[i].value+' + '+x[j].value);
  157.             tmp=x[i].value;//swapping row values
  158.             x[i].value=x[j].value;
  159.             x[j].value=tmp;
  160.             tmp=x[i].row;//swapping row references
  161.             x[i].row=x[j].row;
  162.             x[j].row=tmp;
  163.             i++;
  164.             j--;
  165.         }
  166.     } while(i<=j);
  167.     if(j>L) quickSort(L,j);
  168.     if(i<R) quickSort(i,R);
  169. }
  170.  
  171. /* ]]> */
  172. </script>
  173.  
  174. </head>
  175.  
  176. <body>
  177. <h4> Table Example </h4>
  178. <table class="summary_table">
  179. <thead>
  180.     <tr>
  181.         <th onclick="sortBy(0, 'string', 0, 'quicksort');">column #0</th>
  182.         <th onclick="sortBy(1, 'string', 0, 'quicksort');">column #1</th>
  183.         <th onclick="sortBy(2, 'float', 0, 'quicksort');">column #2</th>
  184.     </tr>
  185. </thead>
  186. <tbody>
  187.     <tr> <td>fres</td> <td>gfs</td>  <td>435</td> </tr>
  188.     <tr> <td>aktm</td> <td> ewa</td> <td>4143a</td> </tr>
  189.     <tr> <td>tjhl</td> <td>fa</td>   <td><span>56 a</span></td> </tr>
  190.     <tr> <td>ahtr</td> <td>mbot</td> <td>98bb7</td> </tr>
  191.     <tr> <td>ae</td>   <td>yyy</td>  <td>5.31</td> </tr>
  192. </tbody>
  193. </table>
  194.  
  195. <script type="text/javascript">
  196. <!--
  197. sortBy(0, 'string', 0, 'quicksort'); // sort the table according to values in column 0, handle values as string, use quicksort algorythm
  198.  // this function must be called when the table already exists (on the document.ready recommended)
  199.  // a lil bit more info about sorting in javascript you can also find on my simple freehosted website: http://sorting.wz.cz (in Slovak language)
  200.  // sorting speed comparation: http://sorting.wz.cz/index.php?p=7
  201.  // enjoy!
  202. document.writeln('<br/>Table sorted.');
  203. //-->
  204. </script>
  205.  
  206. </body>
  207. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement