Thanks for dropping by for another episode of our series on JavaScript Array Objects. We left off discussing five of the thirteen array objects JavaScript has to offer. Here, in this issue, we will make an effort to cover the remaining eight.
More on JavaScript Array Objects - Sort() It Out (Page 4 of 5 )
The sort() object is one those guys that don't need an introduction; its name says it all. But for those of you who are really slow, it sorts the elements in an array. The tricky part of this little fellow is that unless you create a function, it sorts numbers alphabetically. Yeah, my head exploded too. I'll show you how to fix that though. First however, we will use it to sort an array of letters:
<html>
<body>
<script type="text/javascript">
var abet = new Array(6);
abet[0] = "c";
abet[1] = "d";
abet[2] = "x";
abet[3] = "r";
abet[4] = "a";
abet[5] = "b";
document.write("Unsorted: ");
document.write(abet + "<br />" + "<br />");
document.write("Sorted: ");
document.write(abet.sort());
</script>
</body>
</html>
The result of this studious code is:
Unsorted: c,d,x,r,a,b
Sorted: a,b,c,d,r,x
This works the same way for words, as in this example: