Js对象数组排序,数组排序

数组对象排序
var arr = [{name: "zlw", age: 24}, {name: "wlz", age: 25}];
var compare = function (obj1, obj2) {
    var val1 = obj1.name;
    var val2 = obj2.name;
    if (val1 < val2) {
        return -1;
    } else if (val1 > val2) {
        return 1;
    } else {
        return 0;
    }            
} 
console.log(arr.sort(compare));
//输出结果为  [Object { name="wlz", age=25}, Object { name="zlw", age=24}]
上面的代码优化
//这个只能排序age属性值为number类型的,
//如果属性值为数值类型的就会有问题
//问题:只会比较第一位数字大小
var arr = [{name: "zlw", age: 24}, {name: "wlz", age: 25}];
var compare = function (prop) {
    return function (obj1, obj2) {
        var val1 = obj1[prop];
        var val2 = obj2[prop];if (val1 < val2) {
            return -1;
        } else if (val1 > val2) {
            return 1;
        } else {
            return 0;
        }            
    } 
}
arr.sort(compare("age"))//按照 age 进行排序
数组对象排序(没有问题)
var arr = [{name: "zlw", age: 24}, {name: "wlz", age: 25}];
var compare = function (prop) {
    return function (obj1, obj2) {
        var val1 = obj1[prop];
        var val2 = obj2[prop];
        if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
            val1 = Number(val1);
            val2 = Number(val2);
        }
        if (val1 < val2) {
            return -1;
        } else if (val1 > val2) {
            return 1;
        } else {
            return 0;
        }            
    } 
}
arr.sort(compare("age"))
数组排序sort
  •   var arr = new Array('1','3','8','55','2','3','5','66');
      function compare(a, b) {
          return b - a;
      }
      arr = arr.sort(compare);
      console.log(arr.toString())
    
  • 简写
  • arr.sort( (a,b) => a - b )排序
  • arr.sort( (a,b) => b - a )倒序
数组对象排序(用sort)
  • 原理

  • 第一种

    var arr = [
        {name:"zhangsan", age: 21,id:3},
        {name:"lisi", age: 23,id:2},
        {name:"wangwu", age: 20,id:1},
        {name:"zhaoliu", age: 18,id:4},
        {name:"xiaoming", age: 17,id:6},
        {name:"xiaolan", age: 25,id:5}
    ]
    function compare() {
        return function(a, b) {
            return a['id'] - b['id'];
        }
    }
    arr = arr.sort(compare());
    
  • 第二种

    var arr = [
        {name:"zhangsan", age: 21,id:3},
        {name:"lisi", age: 23,id:2},
        {name:"wangwu", age: 20,id:1},
        {name:"zhaoliu", age: 18,id:4},
        {name:"xiaoming", age: 17,id:6},
        {name:"xiaolan", age: 25,id:5}
    ]
    function compare(arg) {
        return function(a, b) {
            return a[arg] - b[arg];
        }
    }
    arr = arr.sort(compare('id'));
    
  • 简写方式(项目中使用最方便)
    arr = arr.sort((() => (a,b)=> a['id'] - b['id'])());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值