Skip to content

Instantly share code, notes, and snippets.

@garystorey
Created July 21, 2017 16:29
Show Gist options
  • Select an option

  • Save garystorey/4341e38b4fadb5e72e9f15da41aebad8 to your computer and use it in GitHub Desktop.

Select an option

Save garystorey/4341e38b4fadb5e72e9f15da41aebad8 to your computer and use it in GitHub Desktop.
function sortFileNames(arr) {
for (var a, t, b, v, result = [], l = arr.length, i = l; i--; ) {
v = arr[i];
t = typeof v;
result[i] = { b: b = t == 'number' || t == 'string', a: a = [], v: v };
if (b) {
(v + '').replace(/(\d+)|\D+/g, function(m, isDigits) {
a.push(isDigits ? parseInt(m, 10) : m);
});
}
}
result.sort(function(a, b) {
if (a.b && b.b) {
a = a.a;
b = b.a;
for (var tA, tB, al = a.length, bl = b.length, i = 0, l = Math.min(al, bl); i < l; i++) {
tA = a[i];
tB = b[i];
if (tA != tB) return tA < tB ? -1 : 1;
}
return al - bl;
}
});
for (; l--; ) result[l] = result[l].v;
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment