freestar freestar - 1 year ago 105
Javascript Question

Javascript / Sort object array

I have created an 5x2


enter image description here

I am trying to sort the competitors as objects by their position property(
) with the following code if
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]


return data;

function sortData() {
var sortedData = getTableData();
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 )

Answer Source

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  = [];

      return parseInt(a.cells[1].innerHTML, 10) - parseInt(b.cells[1].innerHTML, 10);

  for(var i=0; i<data.length; i++) {
td{ border: 1px solid #000; text-align: center; padding: .2em }
<table id="competitors">
<button onclick="sortData()">Sort</button>

What's [] 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download