Skip to content

Instantly share code, notes, and snippets.

@jbt
Created July 14, 2012 17:08
Show Gist options
  • Save jbt/3112153 to your computer and use it in GitHub Desktop.
Save jbt/3112153 to your computer and use it in GitHub Desktop.
Comparator function
/*
Ridiculously useful function
Sorts elements of an array by properties
Usage:
Sort elements by property prop1, then by prop2 if prop1 values are equal
someArrayOfObjects.sort(comparator('prop1', 'prop2'));
*/
function comparator(){
var props = [].slice.call(arguments);
return function(a, b){
var p = props.slice(0), prop;
while(prop = p.shift()){
if(a[prop] < b[prop]) return -1;
if(a[prop] > b[prop]) return 1;
}
return 0;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment