Wednesday, May 23, 2012

Sorting array of custom objects in JavaScript

Say I have an array of Employee Objects:



var Employee = function(fname, age) {
this.fname = fname;
this.age = age;
}

var employees = [
new Employee("Jack", "32"),
new Employee("Dave", "31"),
new Employee("Rick", "35"),
new Employee("Anna", "33")
];





At this point, employees.sort() means nothing, because the interpreter does not know how to sort these custom objects. So I pass in my custom sort function.



employees.sort(function(employee1, employee2){
return employee1.age > employee2.age;
});




Now employees.sort() works dandy.



But what if I also wanted to control what field to be sorted on, passing it in somehow during runtime? Can I do something like this?



employees.sort(function(employee1, employee2, on){
if(on === 'age') {
return employee1.age > employee2.age;
}
return employee1.fname > employee2.fname;
});


I can't get it to work, so suggestions? Design pattern based refactoring perhaps?





No comments:

Post a Comment