-1

I have this table:

<table id="tbl">
  <tr></tr>
  <tr data-pts="3" data-goals="3" data-points="3" data-newgoals="1" data-newpoints="3"></tr>
  <tr data-pts="2" data-goals="3" data-points="3" data-newgoals="1" data-newpoints="1"></tr>
  <tr data-pts="5" data-goals="3" data-points="3" data-newgoals="1" data-newpoints="3"></tr>
  <tr data-pts="4" data-goals="3" data-points="3" data-newgoals="1" data-newpoints="2"></tr>
</table>

I want to sort the table rows by two data attributes: (points+newpoints) DESC, and then (goals+newgoals) DESC (so if there are two table-rows with the same points+newpoints, it will decide who is first by goals+newgoals).

I can't find how to sort it by two attributes.

halfer
  • 19,824
  • 17
  • 99
  • 186
Avni Yayin
  • 469
  • 1
  • 8
  • 18

1 Answers1

1

This should go over the elements and sort the data-pts, I did this quickly so it may not be working 100%, you would ideally want to wrap something similar this into a function allowing yourself to sort by multiple attributes and for performance you wouldn't want to edit the DOM directly in a loop.

You should use cloneNode to make a copy of the html you wish to manipulate, loop over it and sort it then call replaceChild with the clone to change the DOM.

[].forEach.call(document.querySelectorAll('[data-pts]'), function(e) {
    if (e.previousElementSibling && parseInt(e.getAttribute('data-pts')) < parseInt(e.previousElementSibling.getAttribute('data-pts'))) {
        e.parentElement.insertBefore(e, e.previousElementSibling)
    }
})
Geoff448
  • 31
  • 1