Sorting array of custom objects in JavaScript

javascript, object

Solution

function getSortFunction(fieldName) {
    return function(employee1, employee2) {
        return employee1[fieldName] > employee2[fieldName];
    }
}

employees.sort(getSortFunction("myField"));

Another solution is to use Function.prototype.bind if you are not afraid of it :)

function mySorter(fieldName, employee1, employee2) {
    return employee1[fieldName] > employee2[fieldName];
}

employees.sort(mySorter.bind(null, "myField"));

Problem

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?

Original source