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

Chapter 23. Cookies and Creating Your Ow... > Sorting Arrays of Custom Objects

Sorting Arrays of Custom Objects

Say that you want to sort the array of custom friend objects that we’ve created by the rank you’ve assigned to each object. You can do that easily enough in JavaScript using a sorting function (see “Sorting Arrays” in Chapter 19, “The Math, Number, Boolean, and Array Objects”). In this case, I’ll add a button with the caption “Sort by Rank” that calls this function, which sorts the array of objects, array1, with a sorting function named sorter, and displays the sorted array of objects in the text area:

function sort() 
{ 
    array1.sort(sorter) 
    document.form1.textarea1.value = "" 
    for(var loopIndex = 0; loopIndex < array1.length; loopIndex++){ 
        document.form1.textarea1.value += "Name: " + array1[loopIndex].name + " " 
        document.form1.textarea1.value += "Phone: " + array1[loopIndex].phone + " " 
        document.form1.textarea1.value += "Rank: " + array1[loopIndex].rank + "\n" 
    } 
} 

					  


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


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