sorting an array in javascript


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

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"


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.