var obj = [
{
name:"xie",
age:23
},
{
name:"abort",
age:40
},
{
name:"zhu",
age:30
}];
/*方法1*/
function sortByKey(array, key) {
return array.sort(function(a, b) {
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
console.log(sortByKey(obj,"name"));
/*方法2*/
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'}
],obj1 = obj.concat();
obj.sort(sortBy('b', false, parseInt));
console.log(obj);
obj1.sort(sortBy('b', true, String));
console.log(obj1);
/*方法3*/
var people = [
{
name: 'a75',
item1: false,
item2: false
},
{
name: 'z32',
item1: true,
item2: false
},
{
name: 'e77',
item1: false,
item2: false
}];
function sortByKey(array, key) {
return array.sort(function(a, b) {
var x = a[key]; var y = b[key];
return (x < y ? -1 : ((x > y) ? 1 : 0));
});
}
people = sortByKey(people, 'name');
console.log(people);
/*方法4*/
var array = [
{name: 'a', phone: 1, value: 'val_4'},
{name: 'b', phone: 5, value: 'val_3'},
{name: 'd', phone: 3, value: 'val_2'},
{name: 'c', phone: 4, value: 'val_1'}
];
function getSortFun(order, sortBy) {
var ordAlpah = (order == 'asc') ? '>' : '<';
return new Function('a', 'b', 'return a.' + sortBy + ordAlpah + 'b.' + sortBy + '?1:-1');
}
console.log(array.sort(getSortFun('desc', 'phone')));
发表评论
沙发空缺中,还不快抢~