I'm trying to create an array of hours in a day with 30 minute intervals with moment.js and ES6.
Example:
let hours = ["12:00 AM", "12:30 AM", "1:00 AM", "1:30 AM", ..., "11:30 PM"]
I already have this for function:
someFunction () {
  const items = []
  for (let hour = 0; hour < 24; hour++) {
    items.push(moment({ hour }).format('h:mm A'))
    items.push(moment({ hour, minute: 30 }).format('h:mm A'))
  }
  return items
}
But I would like to make it more ES6-like.
I have gotten this far:
someFunction () {
  let timeSlots = new Array(24).fill().map((acc, index) => {
    let items = []
    items.push(moment( index ).format('h:mm A'))
    items.push(moment({ index, minute: 30 }).format('h:mm A'))
  })
  return timeSlots
}
But it outputs:
["1:00 AM", "12:30 AM", "1:00 AM", "12:30 AM", "1:00 AM", "12:30 AM", "1:00 AM", "12:30 AM", "1:00 AM", "12:30 AM", "1:00 AM", "12:30 AM", ...]
function someFunction () {
  const items = [];
  new Array(24).fill().forEach((acc, index) => {
    items.push(moment( {hour: index} ).format('h:mm A'));
    items.push(moment({ hour: index, minute: 30 }).format('h:mm A'));
  })
  return items;
}
                        You can use array#from with array#reduce to generate 30 minutes interval time.
let someFunction = () => {
  return Array.from({length: 24}, (_,i) => i).reduce((r,hour) => {
     r.push(moment({hour, minute: 0}).format('h:mm A'));
     r.push(moment({hour, minute: 30}).format('h:mm A'));
     return r;
  }, []);
}
console.log(someFunction());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With