js排序问题

1、直接排序

  var arr = [1,3,2,5]; 

  function compare(a,b){
    return a - b;//从小到大
    return b - a;//从大到小
  }
  console.log(arr.sort(compare));

2 嵌套排序

按照数组中的某一项value值进行排序,property为属性值

  var arr = [
    {name:'jim',age:27},
    {name:'tony',age:40},
    {name:'jane',age:36},
    {name:'lilei',age:23},
    {name:'Hmm',age:28},
    {name:'jack',age:56},
    {name:'vivian',age:19}
  ];

function compare(property){
  return function(a,b){
    var value1 = a[property];
    var value2 = b[property];
    return value2 - value1;
    }
  }
console.log(arr.sort(compare('age')))

3 嵌套排序,且可以切换正反序

  var arr = [

    {name:'willm',age:27},
    {name:'jay',age:40},
    {name:'Ljj',age:36}

  ];
//不传rev的,则默认按升序排列,传rev则按降序排列
  function compare(property,rev){
    if( rev == undefined ){
      rev = 1;
      }else{
      rev = -1;
      }
  return function(a,b){
    var value1 = a[property];
    var value2 = b[property];
    if(value1 < value2){
    return rev * -1;
  }
    if(value1 > value2){
    return rev * 1;
    }
    return 0;
  }
  }
  console.log(arr.sort(compare('age')));

  

转载于:https://www.cnblogs.com/xumqfaith/p/7274296.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值