ฉันรู้ว่ามีคนถามมานานแล้ว แต่ฉันคิดว่าจะเพิ่มวิธีแก้ปัญหาของฉัน
ฟังก์ชันนี้จะสร้างวิธีการเรียงลำดับแบบไดนามิก เพียงระบุชื่อคุณสมบัติย่อยที่เรียงลำดับได้แต่ละชื่อโดยนำหน้าด้วย +/- เพื่อระบุลำดับจากน้อยไปมากหรือมากไปหาน้อย ใช้ซ้ำได้มากและไม่จำเป็นต้องรู้อะไรเกี่ยวกับโครงสร้างข้อมูลที่คุณรวมเข้าด้วยกัน สามารถพิสูจน์ได้ แต่ดูเหมือนไม่จำเป็น
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 ('- ราคา', '+ ลำดับความสำคัญ', '+ ชื่อ'));
นี้จะจัดเรียง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