0

I've encountered weird stuff that I can't understand and figure out.

I'm trying to sort the table (ascending/descending) - the thing is, it doesn't work as it is supposed to. I've tried debugging and still have no idea why it doesn't work despite code being correct (I think ).

This is the tutorial code that I've used

Everything works great in tutorial, and nothing works for me.

Here is my table before sorting:

Here is my table after sorting (supposedly ascending):

My code is exactly the same as in the tutorial, I've changed nothing in the original function.

During debugging I've noticed that the problem seems to be at this line:

if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase())

which returns true, right in the first iteration (and it shouldn't, since becouse of that my table row ,,Learn ReactJs'' gets moved bottom, and ,,Zinish frontend project'' is moved in first place in table)

I tried changing the ,,greater'' symbol to ,,lower'' symbol, however that doesn't help. I also tried adding:

if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
  shouldSwitch = true;
  break;
 } else { shouldSwitch = false;}

But it also doesn't help. I don't know why it won't work. Please help..

edit: here's pen of my table with the function itself

https://codepen.io/anon/pen/rJQJKx

edit2: in the pen there should be i=0, not i=1 in the for loop, but it still doesn't solve the sorting problem.

Community
  • 1
  • 1
Lovs
  • 351
  • 2
  • 7
  • Next time, please include relevant code directly inside the question, not just on external sites. [ask]. – CBroe Feb 27 '18 at 10:19

1 Answers1

1

This is because some of your cell values contain a leading space, while others don’t:

<td> Zinish frontend project.</td>

<td>Finish my bachelor work by the end of this week otherwise they will kick me.</td>

So of course the first one gets sorted before the second one, because a space character is “less than” any actual letter.

Either remove those spaces from the HTML - or trim both values before you compare them.

CBroe
  • 91,630
  • 14
  • 92
  • 150
  • A man learns out of his own stupidity every day. Thank you very much kind sir, spot on. – Lovs Feb 27 '18 at 10:21