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
CodePudding user response:
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>