나는 이것이 얼마 전에 요청되었다는 것을 알고 있지만 내 솔루션을 추가 할 것이라고 생각했습니다.
이 함수는 정렬 방법을 동적으로 생성합니다. 오름차순 또는 내림차순을 나타 내기 위해 +/-가 추가 된 정렬 가능한 각 하위 속성 이름을 제공하기 만하면됩니다. 재사용이 매우 가능하며 함께 만든 데이터 구조에 대해 알 필요가 없습니다. 멍청한 증거로 만들 수는 있지만 필요하지 않은 것 같습니다.
function getSortMethod(){
var _args = Array.prototype.slice.call(arguments);
return function(a, b){
for(var x in _args){
var ax = a[_args[x].substring(1)];
var bx = b[_args[x].substring(1)];
var cx;
ax = typeof ax == "string" ? ax.toLowerCase() : ax / 1;
bx = typeof bx == "string" ? bx.toLowerCase() : bx / 1;
if(_args[x].substring(0,1) == "-"){cx = ax; ax = bx; bx = cx;}
if(ax != bx){return ax < bx ? -1 : 1;}
}
}
}
사용 예 :
items.sort (getSortMethod ( '-price', '+ priority', '+ name'));
이것은 items가장 낮은 price항목부터 정렬 하고 가장 높은 항목에 연결됩니다 priority. 추가 관계는 항목에 의해 끊어집니다name
항목은 다음과 같은 배열입니다.
var items = [
{ name: "z - test item", price: "99.99", priority: 0, reviews: 309, rating: 2 },
{ name: "z - test item", price: "1.99", priority: 0, reviews: 11, rating: 0.5 },
{ name: "y - test item", price: "99.99", priority: 1, reviews: 99, rating: 1 },
{ name: "y - test item", price: "0", priority: 1, reviews: 394, rating: 3.5 },
{ name: "x - test item", price: "0", priority: 2, reviews: 249, rating: 0.5 } ...
];
라이브 데모 : http://gregtaff.com/misc/multi_field_sort/
수정 : Chrome 문제가 수정되었습니다.