var List = ["F", "60", "59", "6", "7", "7'", "60'", "60a", "c1", "A", "5", "a1", "6.2", "A'", "B", "A1"];
var sortedListe = List.sort(function (a, b) {
var collator = new Intl.Collator('en', { numeric: true, sensitivity: "base" });
return collator.compare(a, b);
});
console.log(sortedListe);
What I get: ["5", "6", "6.2", "7", "7’", "59", "60", "60’", "60a", "A", "A’", "a1", "A1", "B", "c1", "F"]
https://jsfiddle.net/5coraw0z/
PRO: 6.2 comes before 7; 7′ is also in the right place; c1 is between B and F.
CONTRA: Strings beginning with a letter are at the end of the list.
My expected result: ["A", "A’", "a1", "A1", "B", "c1", "F", "5", "6", "6.2", "7", "7’", "59", "60", "60’", "60a"]
2
Answers
If you need non-standard sorting rules, it’s often easier to sort each part of the array separately rather than inventing a convoluted sorting callback:
With this kind of data we could avoid the collator. The logic is to sort the items char by char with fetching as much as possible digit chars. At first sight it could look complicated, but that’s just char by char comparison with alpha/numeric/undefined cases.
The goal was speed, to avoid any intermediate arrays like in the gog’s soluiton.
There’s also an important difference that the gog’s solution splits everything into 2 alpha and numeric strings to compare. While my solution accept any number of alpha/numeric strings combined.