1

Hi I have an array of numbers

let timearray = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23];

But the problem is I am displaying the array value in DOM, but I want it such a way that the values been mapped accordingly. Ex: If 0 -> 12:00am, if its 18 -> 6:00pm. How can I do that? Any idea guys? I can only think of map using if else. But that seems pretty ugly. Any idea guys?

smokiehero
  • 23
  • 3

5 Answers5

3

You need to define your array like this:

const timearray = [
 '12:00am',
 '01:00am',
 '02:00am',
 '03:00am',
...
 '10:00pm',
 '11:00pm',
]
console.log(timearray[3])
// 03:00am
Tomasz
  • 657
  • 3
  • 9
1

Here's an example map function you can use (and improve based on your needs):

const timeArray = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23];
const result = timeArray.map(t => {
  const ampm = t % 12;
  return `${ampm === 0 ? 12 : ampm}:00${t >= 12 ? 'pm' : 'am'}`;
});
console.log(result)
Yaron Schwimmer
  • 5,327
  • 5
  • 36
  • 59
0

This is exactly what Array.map is for:

let timearray = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]

let mapped = timearray.map(function(value) {
    switch (value) {
        case 0: return "12:00am"
        // ..
        case 18: return "6:00pm"
    }
})

Or you can use an object

let timearray = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]

let map = {
    0: "12:00am",
    18: "6:00pm"
}

let mapped = timearray.map(function(value) {
    return map[value]
})

If you simply want to convert 24 hour time to 12 hour time AND NOT MAP THE VALUES then google for "24 hour time to 12 hour time" and you'll find an answer.

Marco
  • 7,007
  • 2
  • 19
  • 49
0

To convert integers to hours in 12-hour format with am/pm format you can use:

let timearray = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23];

timearray.forEach(x => {
  var suffix = x >= 12 ? "pm":"am"; 
  hours = ((x + 11) % 12 + 1) + suffix;
  console.log(hours);
  }
);

Based on code from this answer: Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

user2314737
  • 27,088
  • 20
  • 102
  • 114
0

You may also consider leveraging a library such as, moment.js (https://momentjs.com/) in this situation. Here is an example of usage in your case:

var time = moment(2,"h:hh A");
console.log(time);
// 02:00am

The benefit from this approach is that you would be able to easily format the output, if required to.

jcmortensen
  • 111
  • 7