javascriptarraysfor-loopnullarray-indexing

fill remaining indexes in array with null values


I need to adjust for blank days in my calendar app. There should be 35 blocks to make up the calendar, but I need to fill the array with 30 items inside of that. Is there a method that allows that?

so far this just pushes the days, but you will notice the last days stretch. How can I get blank days in my array? I think i need ensure the calendar is always 35 items.

So I want [null, null, 0, 1, 2, 3, 4, 5...last day in month]. almost like flex end.

Example:

var monthIndex = 0;
var calendarDays = [];
var daysInMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31];


 function updateCalendar() {
      calendarDays = [];
      for (let i = 0; i < daysInMonth[monthIndex]; i++) {
        calendarDays.push(i);
      }
 },

enter image description here


Solution

  • You can use #Array.fill and then map in the values, like

    new Array(35).fill(" ").map((_, i) => i <= daysInMonth[monthIndex] ? i : '')
    

    var calendarDays = [];
    var daysInMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31];
    
    
    function updateCalendar(monthIndex) {
      calendarDays = new Array(35).fill(" ").map((_, i) => i <= daysInMonth[monthIndex] ? i : '');
      return calendarDays;
    }
    
    console.log(updateCalendar(0))
    console.log(updateCalendar(1))