简体   繁体   中英

Custom table sort using jquery or Javascript

I have the following table with three columns (ID, Date, and Source). I want to sort this table based on the Source Column . I don't want to sort either alphabetic or numeric. I want them sorted like all the rows from ON sources will appear first in the table, after then all the rows from MB source, and so on using either Javascript or jquery . I searched almost all the threads related to sorting. But I failed to solve this problem. I am new to this so please help me to get this done. Your help is really appreciated.

<table>
 <tr>
    <th>ID</th>
    <th>Date</th>
    <th>Source</th>
  </tr>
  <tr>
    <td>50</td>
    <td>2012-01-01</td>
    <td>ON</td>
  </tr>
  <tr>
    <td>94</td>
    <td>2013-06-05</td>
    <td>MB</td>
  </tr>
  <tr>
    <td>80</td>
    <td>2011-07-08</td>
    <td>AB</td>
  </tr>
  <tr>
    <td>50</td>
    <td>2012-01-01</td>
    <td>ON</td>
  </tr>
  <tr>
    <td>50</td>
    <td>2012-01-01</td>
    <td>MB</td>
  </tr>
</table>

Can make array of the order since source is known and use that array index to sort by

var sorters =['ON','AB','MB']

var $rows = $('tr:gt(0)').sort(function(a, b){
    var aSrcIdx =sorters.indexOf( $(a).find('td:last').text() );
    var bSrcIdx = sorters.indexOf( $(b).find('td:last').text());

    return aSrcIdx >  bSrcIdx;    
});

$('table').append($rows);

I left the html alone but it could certainly be improved with data attributes to make this more efficient

DEMO

Okay here's how I've done something like this. Given the element a data-* attribute with an integer value of the priority.

Then sort them using js' sort() function like so:

$(elementsToBeSorted).sort(function(a, b){
    return $(a).attr('data-priority') - $(b).attr('data-priority');
}).appendTo('body');

In your case, you could do something like this:

$('tr').not($('.th').parents('tr')).sort(function(a, b){
    return $(a).children('td').last().text() - $(b).children('td').last().text();
}).appendTo('table');

This sorts all rows that are do not contain headings by text within the last table-data element.

I'd recommend to sort source data before putting it into the DOM. Assuming data is array to display, you can write something like this:

var data = [
    {id: 50, date: '2012-01-01', source: 'ON'},
    {id: 94, date: '2013-06-05', source: 'MB'}
];

var sortedData = data.sort(function (a, b) {
    var weights = ['ON','MB'];

    return weights.indexOf(a.source) - weights.indexOf(b.source);
});

This way array sortedData will be ordered according the order of elements in weights .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM