Sams Teach Yourself JavaScript in 24 Hours Free Open Book

Sams Teach Yourself JavaScript in 24 Hours

Previous Page
Next Page

Sorting a Numeric Array

Because the sort method sorts alphabetically, it won't work with a numeric arrayat least not the way you'd expect. If an array contains the numbers 4, 10, 30, and 200, for example, it would sort them as 10, 200, 30, 4not even close. Fortunately, there's a solution: You can specify a function in the sort method's parameters, and that function will be used to compare the numbers. The following code sorts a numeric array correctly:

function numcompare(a,b) {
   return a-b;
}
nums = new Array(30, 10, 200, 4);
sortednums = nums.sort(numcompare);

This example defines a simple function, numcompare, which subtracts the two numbers. After you specify this function in the sort method, the array is sorted in the correct numeric order: 4, 10, 30, 200.

By the Way

JavaScript expects the comparison function to return a negative number if a belongs before b, 0 if they are the same, or a positive number if a belongs after b. This is why a-b is all you need for the function to sort numerically.


Try It Yourself

Sorting and Displaying Names

To gain more experience working with JavaScript's string and array features, you can create a script that enables the user to enter a list of names, and displays the list in sorted form.

Because this will be a larger script, you will create separate HTML and JavaScript files, as described in Hour 3, "Getting Started with JavaScript Programming." First, the sort.html file will contain the HTML structure and form fields for the script to work with. Listing 5.2 shows the HTML document.

Listing 5.2. The HTML Document for the Sorting Example

<html>
<head>
<title>Array Sorting Example</title>
<script type="text/javascript" language="javascript" src="sort.js">
</script>
</head>
<body>
<h1>Sorting String Arrays</h1>
<p>Enter two or more names in the field below,
and the sorted list of names will appear in the
text area.</p>
<form name="theform">
Name:
<input type="text" name="newname" size="20">
<input type="button" name="addname" value="Add"
onclick="SortNames();">
<br>
<h2>Sorted Names</h2>
<textarea cols="60" rows="10" name="sorted">
The sorted names will appear here.
</textarea>
</form>
</body>
</html>

Because the script will be in a separate document, the <script> tag in the header of this document uses the src attribute to include a JavaScript file called sort.js. You will create this file next.

This document defines a form named theform, a text field named newname, an addname button, and a textarea named sorted. Your script will use these form fields as its user interface. Listing 5.3 shows the JavaScript file.

Listing 5.3. The JavaScript File for the Sorting Example

// initialize the counter and the array
var numnames=0;
var names = new Array();
function SortNames() {
  // Get the name from the text field
  thename=document.theform.newname.value;
  // Add the name to the array
  names[numnames]=thename;
  // Increment the counter
  numnames++;
  // Sort the array
  names.sort();
  document.theform.sorted.value=names.join("\n");
}

The script begins by defining two variables with the var keyword: numnames will be a counter that increments as each name is added, and the names array will store the names.

When you type a name into the text field and click the button, the onclick event handler calls the SortNames function. This function stores the text field value in a variable, thename, and then adds the name to the names array using numnames as the index. It then increments numnames to prepare for the next name.

The final section of the script sorts the names and displays them. First, the sort() method is used to sort the names array. Next, the join() method is used to combine the names, separating them with line breaks, and display them in the textarea.

To test the script, save it as sort.js, and then load the sort.html file you created previously into a browser. You can then add some names and test the script. Figure 5.2 shows the result after sorting several names.

Figure 5.2. The output of the name-sorting example.



Previous Page
Next Page
Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y]


     Main Menu
Sams Teach Yourself JavaScript in 24 Hours
Table of Contents
Copyright
About the Author
Acknowledgments
Part I: Introducing the Concept of Web scripting and the JavaScript Language
Part II: Learning JavaScript Basics
Hour 5. Using Variables, Strings, and Arrays
Using Variables
Understanding Expressions and Operators
Data Types in JavaScript
Converting Between Data Types
Using String Objects
Working with Substrings
Using Numeric Arrays
Using String Arrays
Sorting a Numeric Array
Summary
Q&A
Quiz Questions
Quiz Answers
Exercises
Hour 6. Using Functions and Objects
Hour 7. Controlling Flow with Conditions and Loops
Hour 8. Using Built-in Functions and Libraries
Part III: Learning More About the DOM
Part IV: Working with Advanced JavaScript Features
Part V: Building Multimedia Applications with JavaScript
Part VI: Creating Complex Scripts
Part VII: Appendixes
Index


More Books
PHP Hacks
Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
The Koran (Holy Qur'an)
Macromedia Flash 8 Bible
Search Engine Optimization for Dummies
YouTube Traffic
PHP 5 for Dummies
Harry Potter and The Chamber of Secrets
Harry Potter and the Sorcerer's Stone
The Pilgrim's Progress
Wireless Hacks
Flash Hacks. 100 Industrial-Strength Tips & Tools
PayPal Hacks. 100 Industrial-Strength Tips and Tools
Amazon Hacks
Pdf Hacks
The Da Vinci Code
Google Hacks
The Holy Bible
Windows XP For Dummies
Harry Potter and the Half-Blood Prince
Seo Book
Upgrading and Repairing Networks
Macromedia Dreamweaver 8 UNLEASHED
Windows XP Annoyances
Windows XP Hacks
Microsoft Windows XP Power Toolkit
Teach Yourself MS Office In 24Hours
iPod & iTunes Missing Manual
PC Hacks 100 Industrial-Strength Tips and Tools
PC Overclocking, Optimization, and Tuning - 2th Edition
PC Hardware In A Nutshell 3rd Edition
PC Hardware in a Nutshell, 2nd Edition
Upgrading and Repairing PCs
Google for Dummies
MySQL Cookbook
Teach Yourself Macromedia Flash 8 In 24 Hours
PHP CookBook
Sams Teach Yourself JavaScript in 24 Hours
PHP5 Manual
Free Games Paper Airplanes
500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele