Sort an array of objects by an object property / key

A quick snippet for manipulating javascript object data

jQuery,javascript

This is a quick snippet that often comes in handy - you have a bunch of objects which are being added to an array in no particular order, and you want to sort that array into some logical order, using a common property that all of the objects possess. The code is simple:


var array = [(id, name, value),(id, name, value),(id, name, value)];

function SortByName(a, b){
  var aName = a.name.toLowerCase();
  var bName = b.name.toLowerCase();
  return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}

array.sort(SortByName);