這裏有兩個排序功能可能有用:
// sort on values
function srt(desc) {
return function(a,b){
return desc ? ~~(a < b) : ~~(a > b);
};
}
// sort on key values
function keysrt(key,desc) {
return function(a,b){
return desc ? ~~(a[key] < b[key]) : ~~(a[key] > b[key]);
}
}
對於數組您可以排序的 '名稱' 使用:
var arr = [ {name:'bob', artist:'rudy'}
,{name:'johhny', artist:'drusko'}
,{name:'tiff', artist:'needell'}
,{name:'top', artist:'gear'}]
.sort(keysrt('name'));
您還可以結合排序功能:
function srt(desc,key) {
return function(a,b){
return desc ? ~~(key ? a[key]<b[key] : a < b)
: ~~(key ? a[key] > b[key] : a > b);
};
}
並使用
var arr = [ {name:'bob', artist:'rudy'}
,{name:'johhny', artist:'drusko'}
,{name:'tiff', artist:'needell'}
,{name:'top', artist:'gear'}]
.sort(srt(null,'name'));
這裏是一種全在一個解決方案:
function srt(on,descending) {
on = on && on.constructor === Object ? on : {};
return function(a,b){
if (on.string || on.key) {
a = on.key ? a[on.key] : a;
a = on.string ? String(a).toLowerCase() : a;
b = on.key ? b[on.key] : b;
b = on.string ? String(b).toLowerCase() : b;
// if key is not present, move to the end
if (on.key && (!b || !a)) {
return !a && !b ? 1 : !a ? 1 : -1;
}
}
return descending ? ~~(on.string ? b.localeCompare(a) : a < b)
: ~~(on.string ? a.localeCompare(b) : a > b);
};
}
// usage examples
'a,z,x,y,a,b,B,Z,a,i,j,y'.split(',').sort(srt({string:true;}));
//=> ,a,a,b,B,i,j,x,y,y,z,Z
[100,7,8,2,2,0,5,1,6,5,-1].sort(srt());
//=> -1,0,1,2,2,5,5,6,7,8,100
[100,7,8,2,2,0,5,1,6,5,-1].sort(srt({},true}));
//=> 100,8,7,6,5,5,2,2,1,0,-1
var objarr =
[ {name:'bob', artist:'rudy'}
,{name:'Johhny', artist:'drusko'}
,{name:'Tiff', artist:'needell'}
,{name:'top', artist:'gear'}]
.sort(srt({key:'name',string:true}, true));
for (var i=0;i<objarr.length;i+=1) {
console.log(objarr[i].name);
}
//=> logs zeb, top, Tiff, Johnny consecutively
添加標籤, –
JavaScript中,通過它的外觀。 –
這是一個重複的問題:http://stackoverflow.com/questions/5421253/sort-javascript-array-of-objects-based-on-one-of-the-objects-properties – Xavier