1.一维数组排序

timeList=['2017-10-05','2017-10-01','2017-10-03','2017-10-02','2017-10-09'];
timeList.sort();
console.log(timeList);

2.对象数组的排序

sort方法接收一个函数作为参数,这里嵌套一层函数用来接收对象属性名,其他部分代码与正常使用sort方法相同

var arr = [
    {name:'zopp',age:0},
    {name:'gpp',age:18},
    {name:'yjj',age:8}
];

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

当对日期排序就需要处理一下

var arr = [
    {name:'zopp',age:'2017-11-5'},
    {name:'gpp',age:'2017-11-9'},
    {name:'yjj',age:'2017-11-1'}
];

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

vue中的写法

mounted(){
    this.$ajax.get('/service/diagnosis/query/18')
      .then((reps)=>{
        let temp=reps.data.body;
        let temp1=temp.sort(this.sortArray('id'));
        console.log(temp1);
      })
      .catch((error)=>{
        //console.log(error);
      });
    //ajax  
},
methods:{
    sortArray:function(property){
         return function(a,b){
            var value1 = a[property];
            var value2 = b[property];
            return value2 - value1  ;
         }
    }
}
作者 铁血 汉子 2017年11月20日
2024/11/21/07:08:13pm 2017/11/20/6:31:15
0 4382