Return to Kroll Design home page

JavaScript Tutorials

 
« Return

sort method for arrays

The sort method for arrays calls a sort function provided by you, whether you code it from scratch, or get it from somewhere else. Your sorting algorithm's name gets passed as the parameter when you call the sort method (do not put your sort algorithm's name in quotes when you pass it to the sort method). Your sorting algorithm should itself expect two parameters, as JavaScript will loop, calling your algorithm, passing a pair of values to sort each time.

If parameter1 is greater than parameter2 your algorithm should return a positive number.
If parameter1 is less than parameter2 your algorithm should return a negative number.
If parameter1 is equal to parameter2 your algorithm should return a zero.

Once the sort method is done using your sort algorithm, the sort method returns the sorted array.

Code:

<script type="text/javascript">
//<![CDATA[
function mySort(item1, item2) { if (item1 > item2) return 1; if (item1 < item2) return -1; if (item1 == item2) return 0; } myArray = new Array(3, 6, 8, 1, 2); document.write("myArray before being sorted:<br>"); for (i=0; i<myArray.length; i++) { document.write("myArray[", i, "] : ", myArray[i], "<br>"); } myArray.sort(mySort); document.write("<br>myArray after being sorted:<br>"); for (i=0; i<myArray.length; i++) { document.write("myArray[", i, "] : ", myArray[i], "<br>"); } //]]> </script>

Output:



 
« Return


©2012 Kroll Design    info@KrollDesign.net    781.910.3694
Last modified: 12/31/1969 7:00 PM