js array各项是json类型时按某属性排序
发布于 5 年前 作者 xiangjie 510 次浏览 来自 分享

js 的Array.sort(sfunc)指令可实现数组排序。数组各项有可能是:数字,字串,简单json型。其中json型时,可按json某属性排序,该属性可以是数字型抑或字符串型。后面的四个排序函数,都用到这个核心代码:

arr1.sort(sfunc);
function sfunc(a, b){
         return a - b;
}

//  以下代码均已调试通过
var arr1 = [2, 1, 3];
arr1.sort(asort_num("ASC"));
console.log(arr1);                // 1, 2, 3

var arr2 = ["B", "A", "C"];
arr2.sort(asort_str("DESC"));
console.log(arr2)            );   // "C", "B" , "A"

var arr3 = [{name: "Smith", age: 20}, {name: "John", age: 10}, {name: "Anna", age: 30}];
arr3.sort(asort_json_num("age", "ASC"));
console.log(arr3);                // [{name: "John", age: 10}, ...]
                                                     
var arr4 = [{name: "Smith", age: 20}, {name: "John", age: 10}, {name: "Anna", age: 30}];
arr4.sort(asort_json_str("name", "DESC"));
console.log(arr4);                // [{name: "Smith", age: 20}, ...]

function asort_num(stype1){
         // 纯数字的数组排序
         // in   排序方式 : ASC-升序, DESC-降序  
         // out  arr sort
         if(stype1.toLowerCase()=="desc"){
            return function(a, b){return b - a;}
         }else if(stype1.toLowerCase()=="asc"){
            return function(a, b){return a - b;}
         }
}
function asort_str(stype1) {
         // 纯字串的数组排序
         // in   排序方式 : ASC-升序, DESC-降序  
         // out  arr sort
         if(stype1.toLowerCase()=="asc"){
            return function (a, b){if(a>b){return 1;}else if(a<b){return -1;}else{return 0;}}
         }else if(stype1.toLowerCase()=="desc"){
            return function (a, b){if(a>b){return -1;}else if(a<b){return 1;}else{return 0;}}
         }
}
function asort_json_num(property, stype1){
         // 数组各项是简单json型,按某项排序(该项为数字型)
         // in   item-name, sort type(asc/desc)
         // out  arr sort
         if(stype1.toLowerCase()=="asc"){
             return function (a, b){return a[property] - b[property];}
          }else if(stype1.toLowerCase()=="desc"){
             return function (a, b){return b[property] - a[property];}
          }
}
function asort_json_str(property, stype1){
         // 数组各项是简单json型,按某项排序(该项为字符串型)
         // in   item-name, sort type(asc/desc)
         // out  arr sort
         if(stype1.toLowerCase()=="asc"){
            return function (a, b){
               if(a[property]>b[property]){
                  return 1;
               }else if(a[property]<b[property]){
                  return -1;
               }else{
                  return 0;
               }
            }
          }else if(stype1.toLowerCase()=="desc"){
            return function (a, b){
               if(a[property]>b[property]){
                  return -1;
               }else if(a[property]<b[property]){
                  return 1;
               }else{
                  return 0;
               }
            }
          }
}
//  [end]

关于 array.sort(),在ECMA-262(6th Edition/June 2015)标准中有详细描述,见其中的 22.1.3.24 Array.prototype.sort(comparefn)。

[END]

回到顶部