I'm having issue on sorting the array by time object based on the current time. The code works sometimes but sometimes it does not. What is the error in my code, or is there a better method for sorting?
const sortTimeFromNow = (timenow,array) => {
array.sort();
let index = array.findIndex((s) => {
return s.day.sched[0].time.start > timenow;
});
index -= index && 1;
return index ? [...array.slice(index), ...array.slice(0, index)] : array;
};
The idea is to sort it like this:
Example Time
const timenow = new Date() //sample '09:45:33'
Array Schedules
const array = [
{"t":"evtA","sched":[{"day":"TUE","time":{"start":"20:00:35","end":"21:30:39"},"allday":false}] },
{"t":"evtB","sched":[{"day":"TUE","time":{"start":"06:00:59","end":"14:00:59"},"allday":false}] },
{"t":"evtC","sched":[{"day":"TUE","time":{"start":"15:00:59","end":"16:00:21"},"allday":false}] },
{"t":"evtD","sched":[{"day":"TUE","time":{"start":"14:00:59","end":"15:00:21"},"allday":false}] }
]
Call function
const result = sortTimeFromNow(timenow,array)
Sample Result should be
//Example1 '09:45:33'
[
{"t":"evtB","sched":[{"day":"TUE","time":{"start":"06:00:59","end":"14:00:59"},"allday":false}] },
{"t":"evtD","sched":[{"day":"TUE","time":{"start":"14:00:59","end":"15:00:21"},"allday":false}] },
{"t":"evtC","sched":[{"day":"TUE","time":{"start":"15:00:59","end":"16:00:21"},"allday":false}] },
{"t":"evtA","sched":[{"day":"TUE","time":{"start":"20:00:35","end":"21:30:39"},"allday":false}] },
]
//Example2 '15:01:00'
[
{"t":"evtC","sched":[{"day":"TUE","time":{"start":"15:00:59","end":"16:00:21"},"allday":false}] },
{"t":"evtA","sched":[{"day":"TUE","time":{"start":"20:00:35","end":"21:30:39"},"allday":false}] },
{"t":"evtB","sched":[{"day":"TUE","time":{"start":"06:00:59","end":"14:00:59"},"allday":false}] },
{"t":"evtD","sched":[{"day":"TUE","time":{"start":"14:00:59","end":"15:00:21"},"allday":false}] },
]