Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select and sort a column in a table using Javascript

I want to select a particular column of a table and sort it accordingly using Javascript (No frameworks or plugins). Could anyone help me regarding this?

<table>
        <thead>
            <tr>
                <td>Col1</td>
                <td>Col2</td>
                <td>Col3</td>
                <td>Col4</td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Data11</td>
                <td>Data23</td>
                <td>Data53</td>
                <td>Data45</td>
            </tr>
            <tr>
                <td>Data81</td>
                <td>Data42</td>
                <td>Data33</td>
                <td>Data4854</td>
            </tr> 
            <tr>
                <td>Data84681</td>
                <td>Data452</td>
                <td>Data354</td>
                <td>Data448</td>
            </tr> 
            <tr>
                <td>Data1846</td>
                <td>Data25635</td>
                <td>Data3232</td>
                <td>Data44378</td>
            </tr> 
        </tbody>
    </table>
like image 235
Sai Chandra Avatar asked Apr 17 '26 08:04

Sai Chandra


1 Answers

function sortTableByColumn(tableId,columnNumber) { // (string,integer)
  var tableElement=document.getElementById(tableId);
  [].slice.call(tableElement.tBodies[0].rows).sort(function(a, b) {
    return (
      a.cells[columnNumber-1].textContent<b.cells[columnNumber-1].textContent?-1:
      a.cells[columnNumber-1].textContent>b.cells[columnNumber-1].textContent?1:
      0);
  }).forEach(function(val, index) {
    tableElement.tBodies[0].appendChild(val);
  });
}

In your page, add id to the table tag:

<table id="myTable">

From javascript, use:

sortTableByColumn("myTable",3);

tBodies[0] is used because there can be many. In your example there is only one.

If we have var arr=[123,456,789], [].slice.call(arr) returns a copy of arr.

We're feeding it the html-rows-collection, found in tBodies[0] of tableElement.

Then, we sort that array with an inline function that compares two array elements, here: rows (<tr>).

Using cells[columnNumber] we access the <td>s, and textContent to access the text content. I've used columnNumber-1 so you can enter 3 for third column instead of 2, because the index of first element of an array (column 1) is 0...

The forEach goes through the elements of the array, which is by now in order, and appendChild row to the tBody. Because it already exist, it just moves it to the end: moving the lowest value to the end, then moving the second lowest to the (new) end, until it ends with the highest value, at the end.

I hope this is what you want. If so, enjoy!

like image 190
iAmOren Avatar answered Apr 18 '26 20:04

iAmOren