Created
January 6, 2009 15:43
-
-
Save kei-s/43859 to your computer and use it in GitHub Desktop.
Array.prototype.sortByParam
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.sortByParam = function(param) { | |
return this.sortByParams([param]); | |
}; | |
Array.prototype.sortByParams = function() { | |
var params = arguments[0]; | |
if( !params | |
|| (!params.length || params.length == 0) | |
|| typeof params !== 'object' | |
|| !params.constructor | |
|| params.nodeType | |
|| params.item ) { | |
params = Array.prototype.slice.call(arguments); | |
} | |
this.sort(function(a,b){ | |
return function(params){ | |
var _params = params.concat(); | |
if(_params.length == 0) return -1; | |
var param = _params.shift(); | |
if(a[param] == b[param]) { | |
return arguments.callee(_params); | |
} else { | |
return a[param] > b[param] ? 1 : -1; | |
} | |
}(params); | |
}); | |
}; | |
/* Usage | |
[{one: 'a', two: 'c', three: 'd'} | |
,{one: 'b', two: 'a', three: 'e'} | |
,{one: 'c', two: 'b', three: 'a'} | |
,{one: 'c', two: 'a', three: 'c'} | |
,{one: 'a', two: 'c', three: 'b'} | |
].sortByParams('one','two','three'); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment