一种直截了当的方法
var sorted = [{a:0,b:0},{a:2,b:1},{a:1,b:2}].sort( function( a, b ) { if ( a.a == b.a ) return 0; return ( a.a > b.a ) ? 1 : -1; }).reverse();
而且更灵活的方法
// Note: console.log() require Firebug var records = [{a:0,b:0},{a:2,b:1},{a:1,b:2}]; console.log( records ); // Sorty by 'a' ascending sortByProperty( records, 'a' ); console.log( records ); // Sort by 'b' descending sortByProperty( records, 'b', true ); console.log( records ); function sortByProperty( arr, property, descending ) { arr.sort( function( a, b ) { return Boolean( descending ) ? b[property] - a[property] : a[property] - b[property] } ); }
适用于字符串的版本
// Note: console.log() require Firebug var records = [ {a:0,b:0} , {a:2,b:1} , {a:'banana',b:'apple'} , {a:1,b:2} , {a:'apple',b:'banana'} ]; console.log( records ); // Sorty by 'a' ascending sortByProperty( records, 'a' ); console.log( records ); // Sort by 'b' descending sortByProperty( records, 'b', true ); console.log( records ); function sortByProperty( arr, property, descending ) { arr.sort( function( a, b ) { var c = a[property].toString() , d = b[property].toString() if ( c == d ) return 0; return Boolean( descending ) ? d > c ? 1 : -1 : d < c ? 1 : -1 } ); }