Posted By

fengelz on 06/18/10


Tagged

javascript array sorting


Versions (?)

sorting an array in javascript


 / Published in: JavaScript
 

If you need to sort an array in javascript this is how it should be done. Casting toLowerCase() is optional but but necessary if fx "Anne" was spelled "anne"

  1. var arr = ["Anne", "Carl", "Benny"];
  2.  
  3. arr.sort(desc); //returns "Carl","Benny","Anne"
  4. arr.sort(asc); //returns "Anne","Benny","Carl"
  5. alert(arr);
  6.  
  7. function desc(a, b)
  8. {
  9. if(a.toLowerCase() > b.toLowerCase()){return -1;}
  10. else {return 1;}
  11. }
  12.  
  13. function asc(a, b)
  14. {
  15. if(a.toLowerCase() < b.toLowerCase()){return -1;}
  16. else {return 1;}
  17. }

Report this snippet  

You need to login to post a comment.