/ 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"
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
var arr = ["Anne", "Carl", "Benny"]; arr.sort(desc); //returns "Carl","Benny","Anne" arr.sort(asc); //returns "Anne","Benny","Carl" alert(arr); function desc(a, b) { if(a.toLowerCase() > b.toLowerCase()){return -1;} else {return 1;} } function asc(a, b) { if(a.toLowerCase() < b.toLowerCase()){return -1;} else {return 1;} }