js实现的对象数组根据对象的键值进行排序代码

有时候会遇到做展示数组的排序,由大到小和由小到大的切换:

var arr=[{id:1,webName:"蚂蚁部落"},{id:2,webName:"网易"}];

function done(key,desc) {

  return function(a,b){

    //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))  //杠杠的,注意括号就是!

  }

}

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

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

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);