This is my first day coding, and I need help with sorting a table in ascending/descending order. The idea is that when a column is clicked it will sort in ascending order, and then it is clicked again it will sort in descending order, then repeat.
This is the function I have created so far.
/*
* A function to show sort data.
*/
function sortTable(n)
{
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("usersId");
switching = true;
dir = "asc";
while (switching)
{
switching = false;
rows = table.rows;
/*Loop through all table rows (except the
first, which contains table headers):*/
for (i = 1; i < (rows.length - 1); i++)
{
//start by saying there should be no switching:
shouldSwitch = false;
x = rows[i].getElementsByTagName("td")[n];
y = rows[i + 1].getElementsByTagName("td")[n];
if (dir == "asc")
{
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase())
{
shouldSwitch= true;
break;
}
}
else if (dir == "desc")
{
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase())
{
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch)
{
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
//Each time a switch is done, increase this count by 1:
switchcount ++;
}
else
{
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
}
Here is a table example
<table id="table">
<tr>
<th onclick="sortTable(0)">Number</th>
<th onclick="sortTable(1)">Fruit</th>
<th onclick="sortTable(2)">Eater</th>
</tr>
<tr>
<td>2</td>
<td>Apple</td>
<td>JeffVeggies</td>
</tr>
<tr>
<td>1</td>
<td>Grapes</td>
<td>MattTreeHugger</td>
</tr>
<tr>
<td>3</td>
<td>Orange</td>
<td>KevinJuicer</td>
</tr>
</table>
I have doubts about the for
-loop within the while
, but the alternative was nested for
-loops. What is the correct, optimal way of sorting?