0

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

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

That works indeed. I really did not expect the solution to be that "easy". Thank you for that!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.