I have a basic table with x amount of columns. The table needs to be sorted by the value in the first column which is an integer. The sort only needs to happen once in descending order using jQuery or JavaScript without a plug-in.
Position Event
3 Investigation
5 Triage
4 Clinic
1 MDT
2 Other
CodePudding user response:
You can use some spreads ('...') and a simple sort function
Inner spread is to make the rows sortable and outer spread is to change them back to html
The unary is not even needed here because of subtraction (ascending numerical)
window.addEventListener("load",function() {
const tb = document.getElementById("tb");
const rows = tb.querySelectorAll("tr")
tb.append(...[...rows].sort((a,b) => {
const A = a.querySelector("td").textContent;
const B = b.querySelector("td").textContent;
return A-B;
}))
})
<table>
<thead>
<tr>
<th>Position</th>
<th>Event</th>
</tr>
</thead>
<tbody id="tb">
<tr>
<td>3</td>
<td>Investigation</td>
</tr>
<tr>
<td>5</td>
<td>Triage</td>
</tr>
<tr>
<td>4</td>
<td>Clinic</td>
</tr>
<tr>
<td>1</td>
<td>MDT</td>
</tr>
<tr>
<td>2</td>
<td>Other</td>
</tr>
</tbody>
</table>
