我有这个代码来排序一个对象数组。对象中的数据是通道和时间(小时,分钟)。我希望根据从最早到最晚的时间通道进行排序。
以这种方式访问频道数据:
channel_array[icount].data[0].hour
channel_array[icount].data[0].minutes
那个data
对象数组是这样的,并且已经排序了:
[{hour:1, minutes:10},{hour:4, minutes:01}...]
现在我需要的是在数据数组{hour:1, minutes: 10}
的第一个元素上从最早到最晚排序通道。我这样做有三个嵌套循环。但这并不理想。有没有更好的方法进行排序?
var current_time = new Date();
var current_hour = current_time.getHours();
var comp_hour = current_hour - 1;
for (var ih = 0; ih < 24; ih++) {
comp_hour += 1;
if (comp_hour == 24) { comp_hour = 0; }
for (var minutes = 0; minutes < 60; minutes++) {
for (var icount = 0; icount < channel_array.length; icount++) {
if (channel_array[icount].data.length > 0) {
var channel_hour = channel_array[icount].data[0].hour;
var channel_minutes = channel_array[icount].data[0].minutes;
var channel_phase = channel_array[icount].data[0].phase;
var next_day = channel_array[icount].data[0].next_day;
if (channel_phase.toLowerCase() == "pm" && channel_hour != 12) { channel_hour += 12; }
if ( parseInt(channel_hour) == parseInt(comp_hour) && parseInt(channel_minutes) == parseInt(minutes) && next_day != 1 ) {
channel_array_sort.push(channel_array[icount]);
}
}
}
}
}
答案 0 :(得分:6)
好主,这太复杂了!只是passing a custom comparator to Array.sort
怎么样?
老实说,我很难搞清楚你想要排序的阵列,但总的来说,它看起来像这样:
var input = [{hour:1, minutes:10},{hour:4, minutes: 1}, ...];
input.sort(function (a, b)
{
// compare hours first
if (a.hour < b.hour) return -1;
if (a.hour > b.hour) return 1;
// else a.hour === b.hour, so compare minutes to break the tie
if (a.minute < b.minute) return -1;
if (a.minute > b.minute) return 1;
// couldn't break the tie
return 0;
});
N.B。执行就地排序,这意味着修改了原始数组。如果这是不可接受的,只需在排序之前make a copy of the array。
var input = /* same as before */;
var output = input.concat();
output.sort(function ()
{
// same as before
});
解决方案的起点,来自OP:
channel_array_sort = channel_array.concat();
channel_array_sort.sort(function (a, b)
{
if (a.data == undefined || b.data == undefined) return 0;
if (a.data.length <= 0 || b.data.length <= 0) return 0;
// compare hours first
var a_hour = a.data[0].hour;
if (a.data[0].phase == "pm") a_hour += 12;
var b_hour = b.data[0].hour;
if (b.data[0].phase == "pm") b_hour += 12;
if (a_hour < b_hour) return -1;
if (a_hour > b_hour) return 1;
// else a.hour === b.hour, so compare minutes to break the tie
if (a.data[0].minutes < b.data[0].minutes) return -1;
if (a.data[0].minutes > b.data[0].minutes) return 1;
// couldn't break the tie
return 0;
});
var print_sort = JSON.stringify(channel_array_sort);
alert('print_sort b '+print_sort);