js排序

1、一般我们给一维数组排序,直接用arr.sort()方法就可以了:

  

1 // 升序
2 arr.sort(function (a, b) {
3     return a - b;
4 });  
5  
6 // 降序
7 arr.sort(function (a, b) {
8     return b - a;
9 });

示例:

let arr = [2,23,1,6,4,78]
 
let b = a.sort(function (a, b) {
    return a - b;
});  
// [1, 2, 4, 6, 23, 78]

2、有需求是给数组的某个属性排序,用以下方法就可以实现了:

//升序
function compareAscSort(property){
        return function(a,b){
            var value1 = a[property];
            var value2 = b[property];
            return value1 - value2;
        }
    }
 
//降序      
function compareDescSort(property){
        return function(a,b){
            var value1 = a[property];
            var value2 = b[property];
            return  value2 - value1;
        }
    }

使用示例:

arr=[ //排序的数组
  {name:'xx',age:12},
  {name:'as',age:13},
  {name:'sd',age:8}
];
 
asc_sort = arr.sort(compareAscSort("age"));
 
//排序之后的数组
asc_sort=[
  {name: "sd", age: 8},
  {name: "xx", age: 12},
  {name: "as", age: 13}
]
原文地址:https://www.cnblogs.com/onlywu/p/14029489.html