其他分享
首页 > 其他分享> > json数组根据某个字段的值进行排序

json数组根据某个字段的值进行排序

作者:互联网

  1. <meta charset="UTF-8">
    <title>json数组根据某个字段的值进行排序</title> </head> <body> </body> <script type="text/javascript">
    var data = [{
        name: "angular",
        value: 0.58
    }, {
        name: "java",
        value: 0.36
    }, {
        name: "php",
        value: 0.78
    }, {
        name: "python",
        value: 1.78
    }, {
        name: "vue",
        value: 2.78
    }];
    //定义一个比较器--降序排列
    function compare(propertyName) {
        console.log(propertyName)
        return function(object1, object2) {
            var value1 = object1[propertyName];
            var value2 = object2[propertyName];
            if(value2 < value1) {
                return -1;
            } else if(value2 > value1) {
                return 1;
            } else {
                return 0;
            }
        }
    }
    console.info(JSON.stringify(data));
    //使用方法
    data.sort(compare("value"));
    console.info(JSON.stringify(data)); </script> </html>
    

原文:https://blog.csdn.net/qq_38397397/article/details/86155230

标签:return,name,propertyName,字段,value,json,value2,排序,data
来源: https://blog.csdn.net/qq_42916612/article/details/93592846