I have this code to sort an array of objects. The data in the objects is channel and time (hour, minutes). I want the sort to be by channels based on time from earliest to latest.
The channel data is accessed in this way:
channel_array[icount].data[0].hour
channel_array[icount].data[0].minutes
That data object array is like this and is already sorted:
[{hour:1, minutes:10},{hour:4, minutes:01}...]
Now all I need is to sort the channels from earliest to latest on the first element of the data array {hour:1, minutes: 10}. I do this with three nested loops. But this is not ideal. Is there a better way to do the sorting?
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]);
}
}
}
}
}
Good lord, this is overcomplicated! How about just passing a custom comparator to
Array.sort?I’m honestly having a hard time figuring out exactly which array you are trying to sort, but in general, it would look something like this:
N.B. this performs an in-place sort, which means that the original array is modified. If that’s not acceptable, just make a copy of the array before sorting it.
Starting point for the solution, from the OP: