Sort and find closest time from current time

  • A+
Category:Languages

I have an array of times

    ["10:00 PM", "08:00 AM", "12:00 AM", "01:00 AM", "12:00 PM",       "03:00 AM", "07:00 AM", "06:00 PM"] 

I want to sort them and find the nearest time from the current time, For example, Assume the time is now 05:00 PM, the above array should return the 06:00 PM as response.

i can able to sort them with below code

    let sortedArray = arrayOfData.sort(function (a, b) {     return parseInt(a.substring(0, 2)) -      parseInt(b.substring(0, 2));     })  

Can some one suggest a way to sort it properly and also to find the closest time from using the current time? Thanks in advance

 


Just add the difference between current hour and array hours in a separate array and sort it ascending and get the first element from array this will be the most appropriate hour.

Check the following snippet:

times = ["10:00 PM","7:00 PM", "08:00 AM", "12:00 AM", "01:00 AM", "12:00 PM",       "03:00 AM", "07:00 AM", "06:00 PM"];  const currentTime = new Date(); const timeDiff = [];  times.sort((a, b) => {   return a.indexOf('PM'); })  times.filter(time => {   const _meridianPosition = time.indexOf('AM') > -1 ? 'AM' : 'PM';    let _time = parseInt(time);      if(_meridianPosition === 'PM' && _time !== 12) {       _time += 12;     } else if(_meridianPosition === 'AM' && _time === 12) {       _time = 0;     }      const k = Math.abs(currentTime.getHours() - _time);      timeDiff.push({hour: time, diff: k}); });  timeDiff.sort((a,b) => {   return a.diff - b.diff; });  console.log(timeDiff[0].hour); 

Working fiddle: https://jsbin.com/zojawagiyi/6/edit?js,console

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: