Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

388
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!