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为降序排列

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM