Created
February 8, 2012 17:53
-
-
Save ryanflorence/1771621 to your computer and use it in GitHub Desktop.
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
Array.prototype.sortBy = (function() { | |
var sorters = { | |
string: function(a, b) { | |
if (a < b) { | |
return -1; | |
} else if (a > b) { | |
return 1; | |
} else { | |
return 0; | |
} | |
}, | |
number: function(a, b) { | |
return a - b; | |
} | |
}; | |
return function(prop) { | |
var type = typeof this[0][prop] || 'string'; | |
return this.sort(function(a, b) { | |
return sorters[type](a[prop], b[prop]); | |
}); | |
}; | |
})(); |
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
var sortArrayByKey = (function() { | |
var sorters = { | |
string: function(a, b) { | |
if (a < b) { | |
return -1; | |
} else if (a > b) { | |
return 1; | |
} else { | |
return 0; | |
} | |
}, | |
number: function(a, b) { | |
return a - b; | |
} | |
}; | |
return function(ary, prop) { | |
var type = typeof ary[0][prop] || 'string'; | |
return ary.sort(function(a, b) { | |
return sorters[type](a[prop], b[prop]); | |
}); | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also note, this only supports strings and numbers, but you could add more sorters inside the closure for other types.