Created
July 14, 2012 17:08
-
-
Save jbt/3112153 to your computer and use it in GitHub Desktop.
Comparator function
This file contains hidden or 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
/* | |
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