i get some trouble when i try to filtering time now in array time, i have code like this ;
var timeNow = "07"; var timeShift = ["08","10","12","14","16","18","20","22","00","02","04","06"]; var newData =[]; for(var data of timeShift){ if(data >= timeNow){ newData.push(data); } } console.log(newData[0]); // output 08
the problem is output not same with my expectation.
i want :
if timeNow is 08, timeShift output(selected) is 08,
if timeNow is 07, timeShift output(selected) is 06,
if timeNow is 09, timeShift output(selected) is 08,
if timeNow is 23, timeShift output(selected) is 22,
. . . . . . . continued as the structural of data timeNow and timeShift like my expectation in there.
How can i fix the problem ?
Please Help me.
Thank you 🙂
Advertisement
Answer
If you need to find the closest single value which is less or equal to than the given one, you need just a small update to your code:
function getTime(timeNow) { var timeShift = ["08", "10", "12", "14", "16", "18", "20", "22", "00", "02", "04", "06"]; var newTime = '00'; for (var data of timeShift) if (data <= timeNow && data >= newTime) newTime = data; return newTime; } console.log(getTime('08')); console.log(getTime('07')); console.log(getTime('09')); console.log(getTime('23'));