Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an hours + minutes array with moment.js and ES6?

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", ...]

like image 351
Doge Avatar asked Jan 01 '23 12:01

Doge


2 Answers

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;
}
like image 133
Jitesh Manglani Avatar answered Jan 04 '23 05:01

Jitesh Manglani


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>
like image 22
Hassan Imam Avatar answered Jan 04 '23 03:01

Hassan Imam