I'm trying to sort my table by javascript(only javascriptpure, not library and not framework, only javascriptpure).
Each column sort by clicking in every header tag and currently the sort is alphabetical but I need the sort will be numeric or alphabetical or date regardless of it. The data is a Json that come from the other side and could have numeric or alphabetical or date column.
This is my sort code:
function sortMainTable(_num) {
var table, rows, sw, i, x, y;
table = document.getElementById("mainTable");
sw = true;
while (sw) {
sw = false;
rows = table.getElementsByTagName("tr");
for (i = 1; i < (rows.length - 1); i++) {
x = rows[i].getElementsByTagName("td")[_num];
y = rows[i + 1].getElementsByTagName("td")[_num];
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
sw = true;
break;
}
}
}
}
Example json:
places = [{
"city": "Los Angeles",
"country": "USA",
"price:": "130.90",
"date": "02/12/2015"
},
{
"city": "Boston",
"country": "USA",
"price:": "11.40",
"date": "10/04/2014",
},
{
"city": "Chicago",
"country": "USA",
"price:": "320.40"
"date": "06/05/2017",
},
]
As I told above, I need the sort will be numeric or alphabetical or date regardless of it. (if the column is numeric, the table sort is order by numeric column, and if the column is alphabetical, the table sort is order by alphabetical column, if the column is date, the table sort is order by date column)
Any idea?
Thanks.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…