0

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}] },
]
knosmos
  • 598
  • 5
  • 16
Jakegarbo
  • 781
  • 6
  • 17

1 Answers1

0

You should definitely sort using a comparator function. Something like

function sortArray(array) {
  myArray.sort( function(x, y) {
     if(x.date.toISOString().split('T')[1] === y.date.toISOString().split('T')[1] ) {
    return 0;
   } else {
   return x.date.toISOString().split('T')[1] < y.date.toISOString().split('T')[1] ? 1 : -1
   }
  });
}

This case is a little basic, it's assuming you have dates or could create date objects out of your strings. In your case I would do something like

if(Date.now().toISOString().substring(11, 19) < x.time.start) {
 return -1
} else {
// do a normal comparison similar to above, since you know the date your comparing against is past the current time
}

Not a full solution but I hope the idea is there, best of luck!

iamaword
  • 685
  • 3
  • 8