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:
<html>
<body>
<script type="text/javascript">
var abet = new Array(6);
abet[0] = "hamburger";
abet[1] = "hotdog";
abet[2] = "apple";
abet[3] = "carrot";
abet[4] = "juice";
abet[5] = "boar";
document.write("Unsorted: ");
document.write(abet + "<br />" + "<br />");
document.write("Sorted: ");
document.write(abet.sort());
</script>
</body>
</html>
Resulting in:
Unsorted: hamburger,hotdog,apple,carrot,juice,boar
Sorted: apple,boar,carrot,hamburger,hotdog,juice
And here is the issue with numbers. If we code it this way:
<html>
<body>
<script type="text/javascript">
var numby = new Array(7);
numby[0] = "100";
numby[1] = "9";
numby[2] = "20";
numby[3] = "25";
numby[4] = "5000";
numby[5] = "40";
numby[6] = "-40";
document.write("Unsorted: ");
document.write(numby + "<br />");
document.write("Sorted: ");
document.write(numby.sort());
</script>
</body>
</html>
This gives us these erroneous results:
Unsorted: 100,9,20,25,5000,40,-40
Sorted: -40,100,20,25,40,5000,9
Next: Fixing the Issue >>
More JavaScript Articles
More By James Payne