I can’t remember where this came in handy, but I know I needed it at some point. This snippet does exactly what it says, sorts a JavaScript array by the supplied key value.

/**
* Sort an array by a key value
*
* @param array array The array that needs to be sorted
* @param string key The value of the key to sort by
* @return array The sorted array
*/
function sortArrayByKey(array, key) {
return array.sort(function(a, b) {
var x = a[key];
var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}