Posted By

iaian7 on 01/22/10


Tagged

javascript sort array alphanumeric


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

iaian7


Alphanumeric Sorting


 / Published in: JavaScript
 

URL: http://iaian7.com/

  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. }

Report this snippet  

You need to login to post a comment.