Thursday, December 16, 2010

Sorting a javascript array by custom sort function

Suppose you have a javascript array which contains objects of Employee as shown below. Sorting the array can be performed by writing custom sort function.

function Employee(lastName, firstName) {
     this.lastName= lastName;
     this.firstName= firstName;
}
var employeeArray = new Array();
employeeArray.push(new Employee("Kennedy", "John"));
employeeArray.push(new Employee("Marshall", "Kevin"));
employeeArray.push(new Employee("Adams", "Bryan"));

// printing in loop gives Kennedy Marshall Adams
alert(employeeArray[i].lastName);

Sorting the array based on employee's last name

// define the sort function
function employeeLastNameComparator(emp1, emp2){
     var emp1LastNameInLowerCase=emp1.lastName.toLowerCase();
     var emp2LastNameInLowerCase=emp2.lastName.toLowerCase();
     if (emp1LastNameInLowerCase < emp2LastNameInLowerCase){           
            return -1;  
     }  
     if (emp1LastNameInLowerCase > emp2LastNameInLowerCase){
          return 1;
     }
     return 0;
}
employeeArray.sort(employeeLastNameComparator);

// after sort prints Adams Kennedy Marshall
alert(employeeArray[i].lastName);

No comments: