Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get nearest time from array javascript

I have an object like this

var object = {
    "Fajr": "04:29 (WIB)",
    "Sunrise": "05:39 (WIB)",
    "Dhuhr": "11:43 (WIB)",
    "Asr": "14:48 (WIB)",
    "Sunset": "17:48 (WIB)",
    "Maghrib": "17:48 (WIB)",
    "Isha": "18:53 (WIB)",
    "Imsak": "04:19 (WIB)",
    "Midnight": "23:43 (WIB)",
    "Firstthird": "21:45 (WIB)",
    "Lastthird": "01:42 (WIB)"
}

and i want to use moment diff https://momentjs.com/docs/#/displaying/difference/ . But after searching for couple hours I don’t know how to get the nearest time from now.

For example if time now is 11:00 then the time next from the object would be 11:43. How do I achieve that ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  1. Parse out the times from each entry and sort the results
  2. Grab the first one that comes after now
  3. If nothing is found, grab the first one from the sorted results as it indicates the next day
var object = {"Fajr":"04:29 (WIB)","Sunrise":"05:39 (WIB)","Dhuhr":"11:43 (WIB)","Asr":"14:48 (WIB)","Sunset":"17:48 (WIB)","Maghrib":"17:48 (WIB)","Isha":"18:53 (WIB)","Imsak":"04:19 (WIB)","Midnight":"23:43 (WIB)","Firstthird":"21:45 (WIB)","Lastthird":"01:42 (WIB)"};

const matcher = /\d+:\d+/;

const parsed = Object.entries(object)
  .map(([key, time]) => {
    const [hour, minute] = time.match(matcher)[0].split(":").map(Number);
    const date = new Date();
    date.setHours(hour, minute, 0, 0);
    return [key, date];
  })
  .sort((a, b) => a[1] - b[1]);

const now = new Date();
const [next] = parsed.find(([, time]) => now <= time) ?? parsed[0];

console.log("next:", next, object[next]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading