1 <HTML> 2 3 <HEAD> 4 <TITLE>JavaScript Example: Array Sort</TITLE> 5 6 <SCRIPT LANGUAGE="JavaScript"> 7 <!-- hide script from old browsers 8 9 president = new Array(10); 10 president[0] = "Washington"; 11 president[1] = "Adams"; 12 president[2] = "Jefferson"; 13 president[3] = "Madison"; 14 president[4] = "Monroe"; 15 president[5] = "Adams"; 16 president[6] = "Jackson"; 17 president[7] = "Van Buren"; 18 president[8] = "Harrison"; 19 president[9] = "Tyler"; 20 21 // Returns -1,0,1 if the first string is lexicographically 22 // less than, equal to, or greater than the second string, 23 // respectively: 24 function compareStrings(a, b) { 25 if ( a < b ) return -1; 26 if ( a > b ) return 1; 27 return 0; 28 } 29 30 // Return -1,0,1 if the first string is shorter than, equal to 31 // (in length), or longer than the second string, respectively: 32 function compareStringLength(a, b) { 33 if ( a.length < b.length ) return -1; 34 if ( a.length > b.length ) return 1; 35 return 0; 36 } 37 38 // Sort and display array: 39 function sortIt(form, compFunc) { 40 var separator = ";"; 41 if ( compFunc == null ) { 42 president.sort(); // lexicographical sort, by default 43 } else { 44 president.sort(compFunc); // use comparison function 45 } 46 // display results 47 form.output.value = president.join(separator); 48 } 49 50 // end script hiding --> 51 </SCRIPT> 52 53 </HEAD> 54 55 <BODY BGCOLOR="#FFFFFF" 56 onLoad="document.forms[0].output.value = president.join(';')"> 57 58 <H2>An array of character strings</H2> 59 60 Listed below are the first ten Presidents of the United States. <P> 61 62 <FORM> 63 <INPUT TYPE="text" NAME="output" SIZE=100> <P> 64 Click on a button to sort the array: <P> 65 <INPUT TYPE="button" VALUE="Alphabetical" 66 onClick="sortIt(this.form, compareStrings)"> 67 <INPUT TYPE="button" VALUE="Name Length" 68 onClick="sortIt(this.form, compareStringLength)"> 69 <INPUT TYPE="button" VALUE="Chronological" 70 onClick="self.location.reload()"> 71 </FORM> 72 73 <P> <HR> Note: 74 <OL> 75 <LI>Alphabetical: uses JavaScript sort() default method on text strings 76 <LI>Name Length: uses user-defined comparison function 77 <LI>Chronological: reloads original array 78 </OL> 79 80 </BODY> 81 </HTML>