Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

390
Vistas
jQuery: how to sort list text taking into account numerical values

I am using the following script (jQuery 2.1.1) to sort a list with text and numerical values. In theory, sorting works because between "iPhone 11" and "iPhone 6", "iPhone 1" comes before "iPhone 6" but in the real world that does not make sense because 6<11 and "iPhone 6"<"iPhone 11".

$('ul').children("li").sort(function(a, b) {
var A = $(a).text().toUpperCase();
var B = $(b).text().toUpperCase();
return (A < B) ? -1 : (A > B) ? 1 : 0;
}).appendTo('ul');

How sorting should be:

iPhone 6
iPhone 8
iPhone 11
iPhone 12
samsung galaxy s8
samsung galaxy s10
samsung galaxy s20

what sorting returns:

iPhone 11
iPhone 12
iPhone 6
iPhone 8
samsung galaxy s10
samsung galaxy s20
samsung galaxy s8

What would the best approach be? I am thinking of stripping all text and sort based on the integers left but if I did that, in the current list that would make the "galaxy" models appear between "iphone" models (which also makes no sense) like so:

iPhone 6
iPhone 8
samsung galaxy s8
samsung galaxy s10
iPhone 11
iPhone 12
samsung galaxy s20
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Since you have to sort the text where it includes numbers, then do:

return A.localeCompare(B, false, {
  numeric: true
})

You can find more information on localCompare and the options here

So you code will look like:

$('ul').children("li").sort(function(a, b) {
  var A = $(a).text().toUpperCase();
  var B = $(b).text().toUpperCase();
  return A.localeCompare(B, false, {
    numeric: true
  })
}).appendTo('ul');

Demo

$('ul').children("li").sort(function(a, b) {
  var A = $(a).text().toUpperCase();
  var B = $(b).text().toUpperCase();
  return A.localeCompare(B, false, {
    numeric: true
  })
}).appendTo('ul');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>iPhone 6</li>
  <li>iPhone 8</li>
  <li>samsung galaxy s8</li>
  <li>samsung galaxy s10</li>
  <li>iPhone 11</li>
  <li>iPhone 12</li>
  <li>samsung galaxy s20</li>
</ul>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda