I'm trying to create an array of times (strings, not Date
objects) for every X minutes throughout a full 24 hours. For example, for a 5 minute interval the array would be:
['12:00 AM', '12:05 AM', '12:10 AM', '12:15 AM', ..., '11:55 PM']
My quick and dirty solution was to use 3 nested for
loops:
var times = []
, periods = ['AM', 'PM']
, hours = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
, prop = null
, hour = null
, min = null;
for (prop in periods) {
for (hour in hours) {
for (min = 0; min < 60; min += 5) {
times.push(('0' + hours[hour]).slice(-2) + ':' + ('0' + min).slice(-2) + " " + periods[prop]);
}
}
}
This outputs the desired result but I'm wondering if there's a more elegant solution. Is there a way to do this that's:
- more readable
- less time complex
if you have access to
moment
, you can always do something like this:the result is the following array:
To start list from particular time like 3:00 PM and loop quarterly(every 15 minutes):
You could use a single
for
loop,while
loop ,Array.prototype.map()
,Array.prototype.concat()
,String.prototype.replace()
If the interval is only to be set in minutes[0-60], then evaluate the below solution w/o creating the date object and in single loop:
In any case you need to do O(N) operations to enumerate array elements. However, you could iterate through
Date
objects itself.Demo