I have created an 5x2 <table>
with id="competitors"
.
I am trying to sort the competitors as objects by their position property(pos
) with the following code if onclick="sortData()"
event happens:
function getTableData() {
var tab = document.getElementById("competitors");
var data = [];
for(var i=0;i<tab.rows.length;i++) {
var competitor = {
name: tab.rows[i].cells[0],
pos: tab.rows[i].cells[1]
};
data.push(competitor);
}
return data;
}
function sortData() {
var sortedData = getTableData();
sortedData.sort(function(a,b){
return parseInt(a.pos) - parseInt(b.pos);
});
for(var i = 0; i < sortedData.length;i++) {
console.log(sortedData[i].name.innerHTML, sortedData[i].pos.innerHTML);
}
}
The problem is that the console prints out the same table. However, if i do not add the compare function, it is sorted alphabetically. Please help me to understand what is going on. (i have started JS yesterday )