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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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)); | |
}); | |
} |