Solution-1:
var arr = ['sample0', 'sample1', 'sample11', 'sample12', 'sample13', 'sample14', 'sample2', 'sample21', 'sample3']
arr.sort(function (a, b) {
return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
});
console.log(arr);
The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare
Solution-2:
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;
}
arr.sort(naturalCompare);
console.log(arr);
This solution has taken from https://stackoverflow.com/a/15479354/3910232