Sometimes you will encounter a sort of array of impressions, from large to small, and from small to large switching:
vararr=[{id:1,webName:"蚂蚁部落"},{id:2,webName:"网易"}];
functiondone(key,desc) {
returnfunction(a,b){
//returndesc ? ~~(parseInt(a[key]) < parseInt(b[key])) : ~~(parseInt(a[key]) > parseInt(b[key]));解决简单的json数组还行,但是遇到复杂重复比较多的数就不行了
Return desc? ((parseint (A[key]) < parseint (B[key]))? 1: ((parseint (A[key) > parseint (B[key]))? -1:0):( (parseint (A[key]) < parseint (B[key]))?-1: ((parseint (A[key)) > parseint (B[key]))? 1:0)//leverage, note the brackets are!
}
}
console.log(arr.sort(done(‘webName‘,true)));
console.log(arr.sort(done(‘id‘,true)));
console.log(arr.sort(done(‘id‘,false)));
This is a summed up, can be a number of characters can be sorted!
var 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: ‘a‘}, {b: ‘2‘, c: ‘b‘}];obj.sort(sortBy(‘b‘,false,parseInt));console.log(obj);
JS implementation of an array of objects based on the object's key values to sort code