Sort Array Elements (string with numbers), natural sort
This is called "natural sort" and can be implemented in JS like this:
function naturalCompare(a, b) {
var ax = [], bx = [];
a.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { ax.push([$1 || Infinity, $2 || ""]) });
b.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { bx.push([$1 || Infinity, $2 || ""]) });
while(ax.length && bx.length) {
var an = ax.shift();
var bn = bx.shift();
var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
if(nn) return nn;
}
return ax.length - bx.length;
}
/////////////////////////
test = [
"img12.png",
"img10.png",
"img2.png",
"img1.png",
"img101.png",
"img101a.png",
"abc10.jpg",
"abc10",
"abc2.jpg",
"20.jpg",
"20",
"abc",
"abc2",
""
];
test.sort(naturalCompare)
document.write("<pre>" + JSON.stringify(test,0,3));
To sort in reverse order, just swap the arguments:
test.sort(function(a, b) { return naturalCompare(b, a) })
or simply
test = test.sort(naturalCompare).reverse();
You could use String#localeCompare
with options
sensitivity
Which differences in the strings should lead to non-zero result values. Possible values are:
"base"
: Only strings that differ in base letters compare as unequal. Examples:a ≠ b
,a = á
,a = A
."accent"
: Only strings that differ in base letters or accents and other diacritic marks compare as unequal. Examples:a ≠ b
,a ≠ á
,a = A
."case"
: Only strings that differ in base letters or case compare as unequal. Examples:a ≠ b
,a = á
,a ≠ A
."variant"
: Strings that differ in base letters, accents and other diacritic marks, or case compare as unequal. Other differences may also be taken into consideration. Examples:a ≠ b
,a ≠ á
,a ≠ A
.The default is "variant" for usage "sort"; it's locale dependent for usage "search".
numeric
Whether numeric collation should be used, such that "1" < "2" < "10". Possible values are
true
andfalse
; the default isfalse
. This option can be set through an options property or through a Unicode extension key; if both are provided, theoptions
property takes precedence. Implementations are not required to support this property.
var array = ["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"];
array.sort(function (a,b) {
return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
});
console.log(array);