Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
- <head>
- <title> http://stackoverflow.com/questions/11400250/javascript-sort-rows-by-column </title>
- <style type="text/css">
- table {
- width:100%;
- border:1px solid #ccc;
- }
- table thead th {
- background-color: #eee;
- text-align: left;
- cursor:pointer;
- }
- </style>
- <script type="text/javascript">/* <![CDATA[ */
- // global variables for sorting functions
- var x; // array of objects { 'cell value in the sorted column', 'reference to ith table row'}
- var length; // count of table rows
- var dir; // sort direction
- var col=-1; // sorted column
- /////////////////////////////////////////////////////////
- // parameters:
- // column number == 0 | 1 | 2 ....
- // sorted type == "string" | "integer" | "float"
- // direction == 0 | 1 ~ descending or ascending
- // sort algorythm == "bubblesort" | "quicksort"
- /////////////////////////////////////////////////////////
- function sortBy(column_number, sorted_type, direction, algorythm)
- {
- // SET VARIABLES
- var table_elements = document.getElementsByClassName("summary_table");
- var table_element = table_elements[0].tBodies[0];
- var table_rows = table_element.rows;
- length=table_rows.length;
- dir = (col==column_number)? (dir?0:1) :direction; // set user friendly sort direction
- col = column_number;
- //var start = new Date().getTime();//time measure starts
- // INITIALIZE ARRAY
- x = new Array();
- for (var i=0; i<length; i++) { //getting values in the column column_number
- x[i] = new Object();
- x[i].row = table_rows[i]; // references to table rows
- //x[i].value = table_rows[i].cells[col].innerHTML; //value on the row i
- x[i].value = getCellText(table_rows[i].cells[col]); //value on the row i
- x[i].value = x[i].value.replace(/^\s*/g,''); //remove whitespaces alias ltrim (optional)
- // if sorted_type=="string" then no change;
- if (sorted_type=='integer') x[i].value = parseInt(x[i].value,10);
- if (sorted_type=='float') x[i].value = parseFloat(x[i].value);
- //x[i].value = x[i].value.toLowerCase(); // MAKE SEARCHING CASE INSENSITIVE
- }
- //alert('var x == '+x.toSource());
- // SORT ARRAYS
- if (algorythm == 'bubblesort') { bubbleSort(); }
- else if (algorythm == 'quicksort') { quickSort(0,length-1); }
- else { alert('Unsupported sorting algorythm specified, table will be not sorted. '); return; }
- // UPDATING THE TABLE
- //alert('Updating the table. ' + table_element + x.toSource());
- // METHOD 1 - very fast
- var n=document.createElement('tbody'); //here will be faster appending
- for (var i=0; i<length; i++) {
- var r=x[i].row.cloneNode(true);
- n.appendChild(r);
- }
- table_element.parentNode.replaceChild(n,table_element);
- //alert('New table body length is ' + n.rows.length); //test ok
- // METHOD 2 - very slow
- /*
- table_element.innerHTML='';
- for (var i=0; i<length; i++) {
- table_element.appendChild(x[i].row); //this appending is much slower
- }
- */
- //var end = new Date().getTime();//time measure ends
- //alert('row sorting time + table update time = '+(end-start));
- //return (end-start); //return execution time
- }
- /////////////////////////////////////////////////////////
- // getCellText - recursive obtaining text from the <td> element
- // thanks to Stuart Langridge, who has originally programmed this function
- // http://www.kryogenix.org/code/browser/sorttable/
- /////////////////////////////////////////////////////////
- function getCellText(el) {
- var str = '';
- var cs = el.childNodes;
- var l = cs.length;
- for (var i = 0; i < l; i++) {
- if (cs[i].nodeType==1) { //ELEMENT_NODE
- /* if (cs[i].nodeName=='INPUT' && cs[i].attributes.getNamedItem('type') && cs[i].attributes.getNamedItem('type').value=='text') //html form inputbox
- return cs[i].value ? cs[i].value:'';
- else
- */ str += getCellText(cs[i]); // div, p, a...
- }
- else if (cs[i].nodeType==3) {//TEXT_NODE
- str += cs[i].nodeValue;
- }
- return str;
- }
- }
- /////////////////////////////////////////////////////////
- // Bubblesort - sufficient for short tables
- /////////////////////////////////////////////////////////
- function bubbleSort() {
- var ri,rj,tmp;
- for (var i=0; i<length; i++) {
- ri=x[i].value;
- for (var j=i+1; j<length; j++) {
- rj=x[j].value;
- if ((dir==0 && rj<ri) //compare values upward (for dir==0)
- || (dir==1 && rj>ri)) //compare values downward (for dir==1)
- {
- //alert(this.method+' swapping rows '+ri+' + '+rj);
- tmp=x[i].value;//swapping row values
- x[i].value=x[j].value;
- x[j].value=tmp;
- tmp=x[i].row;//swapping row references
- x[i].row=x[j].row;
- x[j].row=tmp;
- ri=rj;//updating ri variable for this pass
- }
- }
- }
- }
- /////////////////////////////////////////////////////////
- // Quicksort - highly recommended for long tables
- /////////////////////////////////////////////////////////
- function quickSort(L,R) {
- var i,j,xp,tmp;
- i=L; j=R;
- xp=x[Math.floor((L+R)/2)].value; /* pivot taken from the middle of unsorted array */
- do {
- if(dir) { //descending sort
- while((x[i].value>xp)&&(i<R)) i++;
- while((x[j].value<xp)&&(j>L)) j--;
- }
- else { //ascending sort
- while((x[i].value<xp)&&(i<R)) i++;
- while((x[j].value>xp)&&(j>L)) j--;
- }
- if(i<=j) {
- //alert('swapping row values '+x[i].value+' + '+x[j].value);
- tmp=x[i].value;//swapping row values
- x[i].value=x[j].value;
- x[j].value=tmp;
- tmp=x[i].row;//swapping row references
- x[i].row=x[j].row;
- x[j].row=tmp;
- i++;
- j--;
- }
- } while(i<=j);
- if(j>L) quickSort(L,j);
- if(i<R) quickSort(i,R);
- }
- /* ]]> */
- </script>
- </head>
- <body>
- <h4> Table Example </h4>
- <table class="summary_table">
- <thead>
- <tr>
- <th onclick="sortBy(0, 'string', 0, 'quicksort');">column #0</th>
- <th onclick="sortBy(1, 'string', 0, 'quicksort');">column #1</th>
- <th onclick="sortBy(2, 'float', 0, 'quicksort');">column #2</th>
- </tr>
- </thead>
- <tbody>
- <tr> <td>fres</td> <td>gfs</td> <td>435</td> </tr>
- <tr> <td>aktm</td> <td> ewa</td> <td>4143a</td> </tr>
- <tr> <td>tjhl</td> <td>fa</td> <td><span>56 a</span></td> </tr>
- <tr> <td>ahtr</td> <td>mbot</td> <td>98bb7</td> </tr>
- <tr> <td>ae</td> <td>yyy</td> <td>5.31</td> </tr>
- </tbody>
- </table>
- <script type="text/javascript">
- <!--
- sortBy(0, 'string', 0, 'quicksort'); // sort the table according to values in column 0, handle values as string, use quicksort algorythm
- // this function must be called when the table already exists (on the document.ready recommended)
- // 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)
- // sorting speed comparation: http://sorting.wz.cz/index.php?p=7
- // enjoy!
- document.writeln('<br/>Table sorted.');
- //-->
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement