美文网首页
js根据指定key对json数组排序

js根据指定key对json数组排序

作者: zzl灬 | 来源:发表于2019-12-26 17:54 被阅读0次
    <script>
        var sort_arry1 = [
            {"num": 1},
            {"num": 7},
            {"num": 3},
            {"num": 2},
        ];
        var sort_arry2 = [
            {"num": 1},
            {"num": 7},
            {"num": 3},
            {"num": 2},
        ];
        var compare = function (json_key,reverse=false) {
            return function (obj1, obj2) {
                var return_num = 0;
                var val1 = obj1[json_key];
                var val2 = obj2[json_key];
                if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
                    val1 = Number(val1);
                    val2 = Number(val2);
                }
                if (val1 < val2) {
                    return_num = -1;
                } else if (val1 > val2) {
                    return_num = 1;
                }
                if(reverse){
                    return -return_num
                }
                else{
                    return return_num
                }
            }
        };
        sort_arry1 = sort_arry1.sort(compare("num"));
        console.log(sort_arry1);
        sort_arry2 = sort_arry2.sort(compare("num",true));
        console.log(sort_arry2);
    </script>
    

    结果

    结果.png

    相关文章

      网友评论

          本文标题:js根据指定key对json数组排序

          本文链接:https://www.haomeiwen.com/subject/wdvkoctx.html