0

I have the following array in Typescript:

this.days_in_month = [
    [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], 
    [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], 
    [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], 
    [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], 
];

I want to loop through it, and for every value create a new, empty, array of length of that value and add that array to another array of arrays.

Eg: the first value is 31 so I would create an empty array 31 things long and add the 31-array to an array of arrays. The next value is 28 so I would then create an array 28 things long and then add the 28-array to the array of arrays so that it now contains the 31-array and the 28-array.

In Python I would use range, but I'm not sure how to do this in Typescript.

So far I have the following ts:

this.days_in_month.forEach(function(value, index, array) {
    console.log(value, index, array);
    no_of_days: number = this.days_in_month(value);
    let days = new Array<number>(no_of_days);
})
1

1 Answer 1

2

You can use Array.prototype.map:

let result = days_in_month.map(
    year => year.map(
        (days) => new Array(days)
    )
);

Bear in mind, the created arrays have undefined values. You would typically generate the required values of the array instead of just initializing an empty array for each month.

Sign up to request clarification or add additional context in comments.

4 Comments

So I guess I don't really want to create an empty array - I'm just used to using placeholders, which I guess is bad coding practice! How would I create an array n long and fill it from another array [M, T, W, T, F, S, S]?
Seems like you're building some sort of calendar widget of sorts. I would generate the data as I need it, not generate for a whole bunch of years, only to use later on just a couple of items in the array.
Yep - I could do that! But then I still wouldn't know how to use arrays in ts like I want to!
Also I don't understand how you mean 'generate'? How can you generate a calendar except by arranging days in some sort of data structure? I could call an API, but then I'd still have to have create varying numbers of DOM elements with loops or from arrays to represent the structure? And the point of this is to create my own calendar!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.