faqts : Computers : Programming : Languages : JavaScript : Language Core : Arrays

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

44 of 54 people (81%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How can I sort an Array of Objects?
How can I sort an Array?

Mar 11th, 2000 07:18
Martin Honnen,


First of all Array objects have a sort method which sorts the Array 
elements treating them as strings.
So 
  var names = new Array ('Nathan', 'James', 'Martin')
sorts with
  names.sort()
as
  alert(names)
then shows.
The sort method of Array objects can take an optional parameter which 
is a comparison function 
  function compareElements (el1, el2) {
    //compare two elements here and return 
    //  -1
    // if el1 should become before el2, 
    // 0
    // if they are equal and
    // 1
    // if el2 should become after el1
  }
to allow you to sort other elements than strings, that is numbers or 
even more complex elements like objects. For instance you have Person 
objects
   function Person (name, home) {
     this.name = name;
     this.home = home;
   }
   function Person_toString () {
     return 'Name: ' + this.name + '\nHome: ' + this.home + '\n';
   }
   Person.prototype.toString = Person_toString;
in an Array
   var persons = 
     new Array (
       new Person ('James Kibo Parry', 'http://www.kibo.com'),
       new Person ('Nathan Wallace', 'http://www.faqts.com'),
       new Person ('Martin Honnen', 'http://javascript.faqts.com')
     );
and now you want to sort on the name so you write your comparison 
function 
   function compareNames (el1, el2) {
     return el1.name < el2.name ? -1 : 
            el1.name == el2.name ? 0 : 1;
   }
and then you call
   alert(persons);
   persons.sort(compareNames);
   alert(persons);   
and see how the persons Array is sorted on the name property of its 
elements. To sort on the home field you simply need another function
   function compareHomes (el1, el2) {
     return el1.home < el2.home ? -1 : 
            el1.home == el2.home ? 0 : 1;
   }
and then
   alert(persons);
   persons.sort(compareHomes);
   alert(persons);
shows the persons Array sorted on the home property of its elements.