对象属性排序

Posted on 2019-01-31 10:59  猫头唔食鱼  阅读(1266)  评论(0编辑  收藏  举报

数组里,有几个对象,需要按照属性排序,可以使用下面方法:

  //按照id从小到大排序
        var arr = [
            { name: "zs", id: '9' },
            { name: "ls", id: '16' },
            { name: "ww", id: '3' },
        ];

        function compare(property) {
            return function (a, b) {
                var value1 = a[property];
                var value2 = b[property];
                return value1 - value2;  // value1-value2是从小到大    如果是从大到小 return value2 -value1
            }
        }

        //正常for循环是没有排序的
        for(let i =0;i<arr.length;i++){
            console.log(arr[i]);
        }
         console.log(arr[0]);//9 
         console.log(arr[1]); //16
         console.log(arr[2]); // 3

         //使用排序方法后,打印的内容,按照id的从小到大排序
        console.log(arr.sort(compare('id')));
        for(let i = 0;i<arr.length;i++){
            console.log(arr.sort(compare('id'))[i]);
        }
        console.log(arr.sort(compare('id'))[0]) // 3
        console.log(arr.sort(compare('id'))[1]) // 9
        console.log(arr.sort(compare('id'))[2]) //16

 

=============== update in 2021.6.3 =======================

 

上面写那么多,实际上几行代码ok

 let arr = [
            {name:'zs',age:12},
            {name:'ls',age:6},
            {name:'ww',age:24},
        ];
        // 从小到大
        let compare = (property)=>(a, b)=> a[property] - b[property] 
        console.log(arr.sort(compare('age')));
        // 从大到小
        let compare2 = (property) =>(a,b) => b[property] - a[property]
        console.log(arr.sort(compare2('age')));