js實現的對象數組根據對象的鍵值進行排序代碼

有時候會遇到作展現數組的排序,由大到小和由小到大的切換:javascript

var arr=[{id:1,webName:"螞蟻部落"},{id:2,webName:"網易"}];java

function done(key,desc) {web

  return function(a,b){json

    //return desc ? ~~(parseInt(a[key]) < parseInt(b[key])) : ~~(parseInt(a[key]) > parseInt(b[key]));解決簡單的json數組還行,可是遇到複雜重複比較多的數就不行了數組

    return desc ? ((parseInt(a[key]) < parseInt(b[key]))?1:((parseInt(a[key]) > parseInt(b[key]))?-1:0)):((parseInt(a[key]) < parseInt(b[key]))?-1:((parseInt(a[key]) > parseInt(b[key]))?1:0))  //槓槓的,注意括號就是!spa

  }code

}排序

console.log(arr.sort(done('webName',true)));ip

console.log(arr.sort(done('id',true)));string

console.log(arr.sort(done('id',false)));

 

這是一個概括總結了的,可字符可數字排序!

var sortBy= function (filed,rev,primer){
   rev = (rev) ? -1 : 1;
   return function (a, b) {
     a = a[filed];
     b = b[filed];
     if ( typeof (primer) != 'undefined' ) {
       a = primer(a);
       b = primer(b);
     }
     if (a < b) { return rev * -1; }
     if (a > b) { return rev * 1; }
     return 1;
   }
};
var obj=[
   {b: '3' , c: 'c' },
   {b: '1' , c: 'a' },
   {b: '2' , c: 'b' }
];
obj.sort(sortBy( 'b' , false ,parseInt));
console.log(obj);
相關文章
相關標籤/搜索