对数组进行排序
此篇文章是 希恩 在 发表的,所在栏目:JavaScript,应用标签:none。

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

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

暂无评论
这儿空空的,快来说两句吧!

发表评论

icon_mrgreen.gificon_neutral.gificon_twisted.gificon_arrow.gificon_eek.gificon_smile.gificon_confused.gificon_cool.gificon_evil.gificon_biggrin.gificon_idea.gificon_redface.gificon_razz.gificon_rolleyes.gificon_wink.gificon_cry.gificon_surprised.gificon_lol.gificon_mad.gificon_sad.gificon_exclaim.gificon_question.gif
© 2022 SHEAN.
本站由 Typecho 强力驱动.
请勿转载本站原创内容,