其他分享
首页 > 其他分享> > js 根据数组对象里的某个属性实现顺序或逆序排序

js 根据数组对象里的某个属性实现顺序或逆序排序

作者:互联网

代码如下:



     function sortBy(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;
            }
        }

 
        var list = [             {                 a:8,                 b:[3,4]             },             {                 a:1,                 b:[1,2]             },             {                 a:18,                 b:[5,6]             }         ]         list.sort(sortBy('a')) // == list.sort(sortBy('a'),true)         console.log(list);

 

效果如下:

 

 

 逆序:

list.sort(sortBy('a'),false)

 

标签:sort,return,attr,rev,list,js,sortBy,排序,逆序
来源: https://www.cnblogs.com/ifeelthecall/p/15067217.html