js键值对数组以键排序

const sortBy = function(filed,rev,primer){
    rev = (rev)?-1:1;
    return function(a,b){
        a = a[filed];
        b = b[filed];
        if (typeof (primer) != 'undefined'){
            a = primer(a);
            b = primer(b);
        }
        if (a < b){
            return rev * -1;
        }
        if(a>b){
            return rev * 1;
        }
        return 1;
    }
};

var obj =[
    {b:'3',c:'c'},
    {b:'1',c:'f'},
    {b:'4',c:'a'}
];
obj.sort(sortBy('b',false,parseInt));
console.log(obj);

你可能感兴趣的:(js键值对数组以键排序)