Alphabetize + numeric dynamic list

Asked

Viewed 104 times

1

Hello, I’m trying to sort a list by date-char. I need it in descending order. I don’t know much about javascript/jquery, but from my research, I got to the code below. But he is returning me the order:C8 C2 B1 B13 A20 a18 A8 a2 A7, needed it to be all in descending order: C8 C2 B13 B1 A20 a18 A8 A7 a2. What I’m doing wrong? Here is the Jsfiddle. Thank you.

$(".pecas li").sort(sort_li).appendTo('.pecas');

function sort_li(a, b) {
  var va = $(a).data('char').toString().charCodeAt(0);
  var vb = $(b).data('char').toString().charCodeAt(0);
  if (va < 'a'.charCodeAt(0)) va += 100;
  if (vb < 'a'.charCodeAt(0)) vb += 100;
  return vb > va ? 1 : -1;
}
li{list-style:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol class="pecas">
  <li class="foto" data-char="a20">a20</li>
  <li class="foto" data-char="a18">a18</li>
  <li class="foto" data-char="c8">c8</li>
  <li class="foto" data-char="a8">a8</li>
  <li class="foto" data-char="a2">a2</li>
  <li class="foto" data-char="a7">a7</li>
  <li class="foto" data-char="b1">b1</li>
  <li class="foto" data-char="c2">c2</li>
  <li class="foto" data-char="b13">b13</li>
</ol>

1 answer

1


One way is to separate the letters from the numeric part. If the letter is equal, it will delete the letter and compare the numeric part and return the larger one first. Otherwise, returns the higher value of the letter by .charCodeAt.

$(".pecas li").sort(sort_li).appendTo('.pecas');

function sort_li(a, b) {
   
   var r = /[a-z]/; // expressão regular para eliminar as letras
   var aD = $(a).data('char'); // valor de data-char em "a"
   var bD = $(b).data('char'); // valor de data-char em "b"
   var va = aD.charCodeAt(0); // valor da letra em "a"
   var vb = bD.charCodeAt(0); // valor da letra em "b"

   if(va == vb){ // se as letras forem iguais
      var aN = parseInt(aD.replace(r, '')); // valor numérico em "a"
      var bN = parseInt(bD.replace(r, '')); // valor numérico em "b"
      return bN > aN ? 1 : -1;
   }

   return vb > va ? 1 : -1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol class="pecas">
  <li class="foto" data-char="a20">a20</li>
  <li class="foto" data-char="a18">a18</li>
  <li class="foto" data-char="c8">c8</li>
  <li class="foto" data-char="a8">a8</li>
  <li class="foto" data-char="a2">a2</li>
  <li class="foto" data-char="a7">a7</li>
  <li class="foto" data-char="d1">d1</li>
  <li class="foto" data-char="d11">d11</li>
  <li class="foto" data-char="z8">z8</li>
  <li class="foto" data-char="b1">b1</li>
  <li class="foto" data-char="c2">c2</li>
  <li class="foto" data-char="b13">b13</li>
</ol>

  • Thank you Sam! It worked perfectly!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.