Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created August 19, 2010 21:07
Show Gist options
  • Select an option

  • Save cowboy/538922 to your computer and use it in GitHub Desktop.

Select an option

Save cowboy/538922 to your computer and use it in GitHub Desktop.
jQuery param sort (for BBQ)
/*!
* jQuery param sort - v0.1 - 8/20/2010
* http://benalman.com/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
// Return a sorted params string, suitable for use as a key or fragment.
// (this will most likely become part of jQuery BBQ)
(function($){
'$:nomunge'; // Used by YUI compressor.
var jq_param = $.param;
jq_param.sorted = function( a, traditional ) {
var arr = [],
obj = {};
$.each( jq_param( a, traditional ).split( '&' ), function(i,v){
var key = v.replace( /(?:%5B|=).*$/, '' ),
key_obj = obj[ key ];
if ( !key_obj ) {
key_obj = obj[ key ] = [];
arr.push( key );
}
key_obj.push( v );
});
return $.map( arr.sort(), function(v){
return obj[ v ];
}).join( '&' );
};
})(jQuery);
// Examples:
console.log( decodeURIComponent( $.param.sorted({z:1,b:2,ab:3,bc:4,ba:5,aa:6,a1:7,x:8}) ) );
console.log( decodeURIComponent( $.param.sorted({z:1,b:[6,5,4],x:2,a:[3,2,1]}) ) );
console.log( decodeURIComponent( $.param.sorted({z:1,b:[6,5,4],x:2,a:[3,2,1]}, true) ) );
console.log( decodeURIComponent( $.param.sorted({a:[[4,[5,6]],[[7,8],9]]}) ) );
@cowboy
Copy link
Author

cowboy commented Aug 20, 2010

This is now in jQuery BBQ!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment