js sort方法根據數組中對象的某一個屬性值進行排序


var arr = [
    {name:'zopp',age:0},
    {name:'gpp',age:18},
    {name:'yjj',age:8}
];
 
function compare(property){
    return function(a,b){
        var value1 = a[property];
        var value2 = b[property];
        return value1 - value2;
    }
}
console.log(arr.sort(compare('age')))

如何根據參數不同,來確定是升序排列,還是降序排序呢?

/**數組根據數組對象中的某個屬性值進行排序的方法
     * 使用例子:newArray.sort(sortBy('number',false)) //表示根據number屬性降序排列;若第二個參數不傳遞,默認表示升序排序
     * @param attr 排序的屬性 如number屬性
     * @param rev true表示升序排列,false降序排序
     * */
    sortBy: function(attr,rev){
        //第二個參數沒有傳遞 默認升序排列
        if(rev ==  undefined){
            rev = 1;
        }else{
            rev = (rev) ? 1 : -1;
        }
         
        return function(a,b){
            a = a[attr];
            b = b[attr];
            if(a < b){
                return rev * -1;
            }
            if(a > b){
                return rev * 1;
            }
            return 0;
        }
    }

 

 

來源:https://www.cnblogs.com/deepalley/p/13559339.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var  arr = [
     {name: 'zopp' ,age:0},
     {name: 'gpp' ,age:18},
     {name: 'yjj' ,age:8}
];
 
function  compare(property){
     return  function (a,b){
         var  value1 = a[property];
         var  value2 = b[property];
         return  value1 - value2;
     }
}
console.log(arr.sort(compare( 'age' )))

  

如何根據參數不同,來確定是升序排列,還是降序排序呢?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**數組根據數組對象中的某個屬性值進行排序的方法
      * 使用例子:newArray.sort(sortBy('number',false)) //表示根據number屬性降序排列;若第二個參數不傳遞,默認表示升序排序
      * @param attr 排序的屬性 如number屬性
      * @param rev true表示升序排列,false降序排序
      * */
     sortBy:  function (attr,rev){
         //第二個參數沒有傳遞 默認升序排列
         if (rev ==  undefined){
             rev = 1;
         } else {
             rev = (rev) ? 1 : -1;
         }
         
         return  function (a,b){
             a = a[attr];
             b = b[attr];
             if (a < b){
                 return  rev * -1;
             }
             if (a > b){
                 return  rev * 1;
             }
             return  0;
         }
     }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM