javascript natural sort


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



Copy this code and paste it in your HTML
  1. Array.prototype.naturalSort= function(){
  2. var a, b, a1, b1, rx=/(\d+)|(\D+)/g, rd=/\d+/;
  3. return this.sort(function(as, bs){
  4. a= String(as).toLowerCase().match(rx);
  5. b= String(bs).toLowerCase().match(rx);
  6. while(a.length && b.length){
  7. a1= a.shift();
  8. b1= b.shift();
  9. if(rd.test(a1) || rd.test(b1)){
  10. if(!rd.test(a1)) return 1;
  11. if(!rd.test(b1)) return -1;
  12. if(a1!= b1) return a1-b1;
  13. }
  14. else if(a1!= b1) return a1> b1? 1: -1;
  15. }
  16. return a.length- b.length;
  17. });
  18. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.