Alphanumeric Sorting


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function sortAlphaNum(a, b) {
  2. var x = a.split("/");
  3. var y = b.split("/");
  4. x = x[x.length-1].replace(/\\\s/g," ").split(/(\d )/); // the split formatting is imperative, everything else can change
  5. y = y[y.length-1].replace(/\\\s/g," ").split(/(\d )/); // the split formatting is imperative, everything else can change
  6. for (var i in x) {
  7. if (x[i] && !y[i] || isFinite(x[i]) && !isFinite(y[i])) {
  8. return -1;
  9. } else if (!x[i] && y[i] || !isFinite(y[i]) && isFinite(y[i])) {
  10. return 1;
  11. } else if (!isFinite(x[i]) && !isFinite(y[i])) {
  12. x[i] = x[i].toLowerCase();
  13. y[i] = y[i].toLowerCase();
  14. if (x[i] < y[i]) return -1;
  15. if (x[i] > y[i]) return 1;
  16. } else {
  17. x[i] = parseFloat(x[i]);
  18. y[i] = parseFloat(y[i]);
  19. if (x[i] < y[i]) return -1;
  20. if (x[i] > y[i]) return 1;
  21. }
  22. }
  23. return 0;
  24. }

URL: http://iaian7.com/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.