js 数组中的值排序

//对数组中的多个对象对某一个字段按照字母先后顺序排序

var array = [
        {"id":"111","user":"D"},
        {"id":"222","user":"B"},
        {"id":"111","user":"A"},
        {"id":"333","user":"C"},
        {"id":"444","user":"F"},
        {"id":"555","user":"E"}
    ];

//对数组中的user字段进行排序

    arr.sort(function(a,b){
            return a.user.localeCompare(b.user)
        });


//排序后的结果
    var array = [
        {"id":"111","user":"A"},
        {"id":"222","user":"B"},
        {"id":"333","user":"C"},
        {"id":"111","user":"D"},
        {"id":"555","user":"E"},
        {"id":"444","user":"F"}
        ];
//按id的数字大小升序或者是降序排序

      function compare(property,desc) {
            return function (a, b) {
                var value1 = a[property];
                var value2 = b[property];
                if(desc==true){
                    // 升序排列
                    return value1 - value2;
                }else{
                    // 降序排列
                    return value2 - value1;
                }
            }
        }

        arr.sort(compare("id",true));    //id 为数组中需要排序的字段,true为升序,false为降序排列

 

posted @ 2020-09-29 11:28  _情书  阅读(1692)  评论(0编辑  收藏  举报