jdavis jdavis - 4 months ago 117
Javascript Question

Javascript - sort objects in an array alphabetically on one property of the array

Let's say you have a javascript class like this...

var DepartmentFactory = function(data) {
this.id = data.Id;
this.name = data.DepartmentName;
this.active = data.Active;
}


Let's say you then create a number of instances of that class and store them in an array...

var objArray = [];
objArray.push(DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true}));
objArray.push(DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true}));
objArray.push(DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true}));
objArray.push(DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true}));


So I now would have an array of objects created by DepartmentFactory. How would I go about using the array.sort() method to sort this array of objects by the DepartmentName property of each object?

The array.sort() method works just fine when sorting an array of strings...

var myarray=["Bob", "Bully", "Amy"];
myarray.sort(); //Array now becomes ["Amy", "Bob", "Bully"]


But how do I make it work with a list of objects?

Thanks.

ob. ob.
Answer

you would have to do something like this:

objArray.sort(function(a, b) {
    var textA = a.DepartmentName.toUpperCase();
    var textB = b.DepartmentName.toUpperCase();
    return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});

note: changing the case (to upper or lower) ensures a case insensitive sort.

Comments