Ad

JQuery Sort Items By Last Name

- 1 answer

I want to have sorting on the last name and text to be replaced but I am not able to do it. I have tried following.

HTML

<div id="sort-by-name">
  <table>
    <tbody>
      <tr>
        <tr>
          <td class="names">
            <span class="toggle"></span> Betty j. Sean
          </td>
        </tr>
        <tr>
          <td class="names">
            <span class="toggle"></span> Ali Khan
          </td>
        </tr>
        <tr>
          <td class="names">
            <span class="toggle"></span> Will Turner
          </td>
        </tr>
    </tbody>
  </table>
</div>

// Sort names

var items = [];
$('#ByMember table tbody .irwMemberName').each(function () {
    items.push($(this).html());
});
items.sort();
console.log(items);

I have also try adding a class to last name word. Then applied above sort function it actually sorts all last names but how I can sort whole by that and replace.

$("#sort-by-name table tbody .names").html(function(index, old) {
    return old.replace(/(\b\w+)$/, '<span class="name_identifier">$1</span>');
});

Please let me know if I am not clear. Also Ignore any typo's I have modified code here for post.

Ad

Answer

You can do it like this. Check fiddle: Fiddle

var els = $("#sort-by-name table tbody tr")
.sort(function(a,b){
    var t1 = $(a).find('.names')[0].innerText.split(' ').pop(),
            t2 = $(b).find('.names')[0].innerText.split(' ').pop();

    if(t2 < t1) {
        return 1;
    } else {
      return -1;
    }
})
.each(function() {
  var t = this.innerText.replace(/(\w+)$/, '<span class="name_identifier">$1</span>');
  return $(this).html( t );
});
$('#bodyid').html(els);
Ad
source: stackoverflow.com
Ad