我有一个像这样的对象数组:
var array = [
{minutes: 45, hours: 4, meridiem: "PM"},
{minutes: 00, hours: 8, meridiem: "AM"},
{minutes: 45, hours: 8, meridiem: "AM"},
{minutes: 30, hours: 3, meridiem: "PM"},
{minutes: 15, hours: 11, meridiem: "AM"},
{minutes: 00, hours: 1, meridiem: "PM"}
]
基本上我需要按时间排序,最早的第一个。因此,如果小时和经度相等,那么按AM / PM然后按小时计算,然后按分钟计算。
这是我尝试过的
this.currentTours.sort(function(a,b) {
if (a.meridiem != b.meridiem) {
return 1
}
if ((a.dateR.meridiem == b.dateR.meridiem) && a.dateR.hours !=
b.dateR.hours) {
return 1
}
if (((a.dateR.meridiem == b.dateR.meridiem) && a.dateR.hours !=
b.dateR.hours) && a.dateR.minutes != b.dateR.minutes) {
return 1
}
return a.dateR.meridiem - b.dateR.meridiem
})
越过1层属性就是我被困住的地方。
答案 0 :(得分:3)
您可以使用链式方法进行嵌套排序,并对12 am or pm进行小时校正。这些值被解释为零。
(a.hours < 12) * a.hours
var array = [{ minutes: 45, hours: 4, meridiem: "PM" }, { minutes: 00, hours: 8, meridiem: "AM" }, { minutes: 45, hours: 8, meridiem: "AM" }, { minutes: 30, hours: 3, meridiem: "PM" }, { minutes: 15, hours: 11, meridiem: "AM" }, { minutes: 00, hours: 1, meridiem: "PM" }, { minutes: 00, hours: 12, meridiem: "PM" },{ minutes: 00, hours: 12, meridiem: "AM" }];
array.sort(function (a, b) {
return (b.meridiem === 'AM') - (a.meridiem === 'AM')
|| (a.hours < 12) * a.hours - (b.hours < 12) * b.hours
|| a.minutes - b.minutes;
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
您可以在if
方法中使用简单的Array.prototype.sort
语句来考虑多个属性。
如果两个属性完全相同,请咨询下一个最重要的属性以打破这种关系。
var array = [
{ minutes: 45, hours: 4, meridiem: "PM" },
{ minutes: 00, hours: 8, meridiem: "AM" },
{ minutes: 45, hours: 8, meridiem: "AM" },
{ minutes: 30, hours: 3, meridiem: "PM" },
{ minutes: 15, hours: 11, meridiem: "AM" },
{ minutes: 00, hours: 1, meridiem: "PM" }
];
array.sort(function(a, b) {
if (a.meridiem !== b.meridiem)
return a.meridiem === 'AM' ? -1 : 1;
if (a.hours !== b.hours)
return a.hours - b.hours;
return a.minutes - b.minutes
});
console.log(array);