• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

3. Arrays and Objects > 3.5. Sorting a Simple Array

Sorting a Simple Array

NN 2, IE 4

Problem

You want to sort an array of numbers or strings.

Solution

To sort an array of numbers from lowest to highest, use the plain sort( ) method of the array object:

myArray.sort( );

This action modifies the order of the items within the array, and its original order cannot be restored unless your scripts have preserved that information elsewhere. Sorting a multidimensional array sorts only the outermost level.

Discussion

You can use the same parameter-less method on an array of string items, but the sorting is performed according to the ASCII values of the string characters. Therefore, if the strings in the array are not homogenous with respect to case, you may receive the array sorted such that all strings starting with uppercase letters sort ahead of those starting with lowercase letters (because ASCII values for uppercase letters are smaller than those for lowercase letters, as shown in Appendix A). For more complex and numeric sorting, however, you need to define a comparison function and invoke it from the sort( ) method.


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint