Skip to content Skip to sidebar Skip to footer

Javascript Generate Array Of Hours In The Day Starting With Current Hour

Hi I'm trying to generate an array of every hour of the day. However, I want it to start with the current hour. For example, if the current time is 2:00 pm, the array should star

Solution 1:

Pretty straight-forward. See comments inline:

var result = [];                      // Results will go herevar nowHour = newDate().getHours();  // Get current hour of the day// Loop from current hour number to 23for(var i = nowHour; i < 24; i++){
  result.push(i + "00");  // Put loop counter into array with "00" next to it
}

console.log(result); // show results

Solution 2:

You can use fill and map of Array.Prototype Something like below.

Array(24-newDate().getHours()).fill().map((e,i)=>i+newDate().getHours());

var currHour=newDate().getHours();
console.log(Array(24-currHour).fill().map((e,i)=>i+currHour+"00"));

Solution 3:

It can be done reasonably efficiently in a single statement, including leading zeros on hours before 10:00, and generically using Array.from with an optional callback, e.g.

console.log(
  Array.from(Array(24-newDate().getHours()),(x,i)=>('0'+(23-i)).slice(-2)+'00').reverse()
);

Unfortunately it still creates 2 arrays, the first is an empty array of the required length that is then used to generate the second array with the required values, so not much of a performance hit.

If there was a forEvery method that didn't skip non-existant properties in the same way from doesn't, it could be one with just one Array (just like a for loop does).

Post a Comment for "Javascript Generate Array Of Hours In The Day Starting With Current Hour"