Alphabetic + numeric list dynamic

1

Hello, I'm trying to sort a list by char-date. I need you to keep it in descending order. I do not understand much of javascript / jquery, but through my searches, I got to the code below. But he is returning the order to me: c8 c2 b1 b13 a20 a18 a8 a2 a7, he needed everything to be in descending order: c8 c2 b13 b1 a20 a18 a8 a7 a2. what am I doing wrong? Here is 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><olclass="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>
    
asked by anonymous 02.09.2018 / 18:59

1 answer

1

One way is to separate the letters from the numerical part. If the letter is the same, it will delete what is letter and compare the numerical part and return whichever is greater first. Otherwise, returns the largest 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><olclass="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>
    
02.09.2018 / 19:48