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);
相关文章
相关标签/搜索