//*** This code is copyright 2003 by Gavin Kistner, gavin@refinery.com //*** It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt //*** Reuse or modification is free provided you abide by the terms of that license. //*** (Including the first two lines above in your source code satisfies the conditions.) // Sort an array of objects by multiple criteria // Pass in a single array of parameters, or multiple individual parameters // Each parameter may be a string name for the property, or a custom object with a single property; // the property value is 0 to sort descending, 1 to sort ascending // (See examples below.) // Returns a function pointer suitable for passing to Array.sort(...); // Note that this function calls new Function(...) which is akin to eval() and // hence horrid, gross, terrible, shitty, slutty, and uneducative. But it does. function SortBy(){ var args = (arguments.length==1 && arguments[0].constructor==Array)?arguments[0]:arguments; var body = "return "; for (var i=0,len=args.length;i')+"b."+colName+"?-1:a."+colName+(sortAsc?'>':'<')+"b."+colName+"?1:"; } return new Function('a','b',body+0); } /* EXAMPLES ******************************************************** var people = [ { name:'Bob', age:12, weight:1 }, { name:'Gavin', age:30, weight:170 }, { name:'Susan', age:19, weight:120 }, { name:'Lisa', age:29, weight:135 }, { name:'Lisa', age:45, weight:150 }, { name:'Dave', age:12, weight:170 }, ]; people.sort( SortBy('name','age') ); // Same as: people.sort( SortBy( ['name','age'] ) ); // {name:'Bob',age:12,weight:1}, // {name:'Dave',age:12,weight:170}, // {name:'Gavin',age:30,weight:170}, // {name:'Lisa',age:29,weight:135}, // {name:'Lisa',age:45,weight:150}, // {name:'Susan',age:19,weight:120} people.sort( SortBy( {age:0}, {weight:1} ) ); // {name:'Lisa',age:45,weight:150}, // {name:'Gavin',age:30,weight:170}, // {name:'Lisa',age:29,weight:135}, // {name:'Susan',age:19,weight:120}, // {name:'Bob',age:12,weight:1}, // {name:'Dave',age:12,weight:170} // You can even mix strings with object/sort direction pairs people.sort( SortBy( 'age' , {name:0} ) ); people.sort( SortBy( ['age',{name:0}] ) ); ******************************************************************/