0

I have created an 5x2 <table> with id="competitors".

enter image description here

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 )

fredmaggiowski
  • 2,232
  • 3
  • 25
  • 44
freestar
  • 418
  • 3
  • 18

1 Answers1

0

When sorting, you were doing parseInt of HTML elements instead of their contents. Here is how I would do it:

function sortData(){
  var table = document.getElementById('competitors'),
      data  = [].slice.call(table.rows);

  data.sort(function(a,b){
      return parseInt(a.cells[1].innerHTML, 10) - parseInt(b.cells[1].innerHTML, 10);
  });

  for(var i=0; i<data.length; i++) {
      table.appendChild(data[i]);
  }
}
td{ border: 1px solid #000; text-align: center; padding: .2em }
<table id="competitors">
  <tr><td>Greg</td><td>4</td></tr>
  <tr><td>John</td><td>10</td></tr>
  <tr><td>Sarah</td><td>6</td></tr>
  <tr><td>Ben</td><td>2</td></tr>
  <tr><td>Jack</td><td>1</td></tr>
</table>
<br>
<button onclick="sortData()">Sort</button>

What's [].slice.call(table.rows) for?

table.rows returns an HTMLCollection, which cannot be sorted. This allows you to convert it to an Array -> Most efficient way to convert an HTMLCollection to an Array

Why use appendChild?

When you do appendChild of an element, it does not duplicate it, it moves it. This allows you to reorder your elements.

Community
  • 1
  • 1
blex
  • 24,941
  • 5
  • 39
  • 72