Sorting li into a div

3

I need to sort alphabetically a div , I use the following strategy, I put in a div with display: none all li, so after inserting all in html , I while to while it has li in that div it will check which is greater, the greater, identifying it adds in another div , which is as display:block after I remove from div with display:none and stay in this loop.

My code is below:

while($('#check_presencaNone li').length > '0'){
  $('#check_presencaNone li').each(function(i){
     if($(this).text().toUpperCase() < valor){
       valor = $(this).text().toUpperCase();
       ponteiro = $(this);
     }
  });
  ponteiro.clone().appendTo('#check_presenca');
  ponteiro.remove();   
  console.log($('#check_presencaNone li').length);
}
  

When executing it is getting in an infinite loop, and I am not able to identify the error. What's wrong?

    
asked by anonymous 14.01.2016 / 16:53

2 answers

1

The first point that would solve your question would be to change the while code to the below code:

for(i = 0; i <= $('#check_presencaNone li').length; i++) {
  $('#check_presencaNone li').each(function(i){
     if($(this).text().toUpperCase() < valor){
       valor = $(this).text().toUpperCase();
       ponteiro = $(this);
     }
  });
  ponteiro.clone().appendTo('#check_presenca');
  ponteiro.remove();   
  console.log($('#check_presencaNone li').length);
}
    
14.01.2016 / 18:09
0

Actually I had some questions of logic along with the response from our friend @Oto I came to this resolution.

It was enough for min to zero the value of the variable valor , because when it first happened and identified the smaller one, it selected the pointer, so every time it ran the same pointer to populate the screen. so the code with the correct solution looks like this.

var ponteiro = null,
valor = 'ZZZZZZZZ';
while( $('#check_presencaNone li').length > 0) {
 $('#check_presencaNone li').each(function(i){
   if($(this).text().toUpperCase() < valor){
      valor = $(this).text().toUpperCase();
      ponteiro = $(this);
   }
 });
 ponteiro.clone().appendTo('#check_presenca');
 ponteiro.remove();
 valor = 'ZZZZZZZZ';
}
    
14.01.2016 / 18:21