Iterating through a 2D Typescript array to create a new array with values extracted from specific indices

Here's an array I've defined 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], 
];

My goal is to iterate through this array and for each value, generate a new empty array with a length equal to the value. These arrays will then be added to another array.

For example, if the first value is 31, I would create an empty array with 31 elements and add it to the array of arrays. Then for the next value, let's say 28, I would create a new array with 28 elements and add it to the array so that now it contains both the 31-element array and the 28-element array.

In Python, I would use the range function for this task, but I'm uncertain how to achieve the same result in Typescript.

Here is what I have attempted so far in Typescript:

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);
})

Answer №1

If you need to create an array with a certain number of days for each month, you can utilize the Array.prototype.map method:

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

It's important to note that the arrays created using this approach will contain undefined values. To populate the arrays with specific values, you should adjust the logic accordingly instead of merely initializing empty arrays.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Identify the element in the array that corresponds to the current route

Within an array, I have various routes such as: /app/manual/:id /app/manuals/:id /app/feedback ... In my react.js application, I am looking to compare the location.pathname with the paths in my array and retrieve the title associated with the matching pa ...

How can I optimally transfer a numpy array to a C++ function and receive a numpy array as the result?

After creating a shared library, I am utilizing it in the following manner: class CAudioRecoveryStrategy(AbstractAudioRecoveryStrategy): def __init__(self): array_1d_double = npct.ndpointer(dtype=numpy.double, ndim=1, flags='CONTIGUOUS&ap ...

Is there a method to categorize class methods' parameters in a universally applicable manner?

Consider the code snippet below. class MyClass { method1(arg1: string, arg2: number, arg3: number) {} method2(arg1: string, arg2: number, arg3: number) {} } I want to abstract out the argument types arg1: string, arg2: number, arg3: number for re ...

The initial rendering of components is not displayed by Vue Storybook

The functionality of the storybook is effective, but initially, it fails to "render" the component. By examining the screenshot, we can deduce that the component-template is being utilized in some way, as otherwise, the basic layout of the component would ...

Changing a JSON Array of Objects into a List of Strings

I am currently working on extracting data from JSON and converting it into a Java ArrayList. String query = "SELECT attributes FROM common_attr_test"; PreparedStatement preparedStatement = (PreparedStatement) conn.prepareStatement(query); preparedStatemen ...

Setting 2D string arrays with char pointers

I am attempting to populate a 2D array of strings using the following approach: char *text_data[10][4]; //10 rows, 4 columns //Assigning values to all rows for (i = 0; i < 10; i++) { strcpy(text_data[i][0], "a"); strcpy(text_data[i][1], "xyz") ...

Transforming an HTMLCollection into an array using JavaScript

I am looking to retrieve all the HTML elements that have the class "Box" and then convert that collection into an Array so I can access each element by its position. Below is the code I wrote: function BoxAppearence() { var BoxCollection = docume ...

typescript page objects in protractor are showing an undefined property

Hey there, I'm facing an issue while using POM in Protractor with TypeScript in Angular CLI. The error I'm encountering is "Cannot read property 'sendUsername' of undefined". Since I'm new to TypeScript, can someone guide me on how ...

Extracting the actual data type from a property value in a typed object: a step-by-step guide

type Animal = { name: string } // received from external source const cat: Animal = { name: 'Cat' as const } const dog = { name: 'Dog' as const } type CatName = typeof cat.name // = string, not 'Cat' !!! type DogN ...

Apply CSS styles conditionally to an Angular component

Depending on the variable value, I want to change the style of the p-autocomplete component. A toggle input determines whether the variable is true or false. <div class="switch-inner"> <p [ngClass]="{'businessG': !toggle }" clas ...

Invoke the function once the database information has been retrieved

I am new to Node.js and I am attempting to execute a function after running a select query using the code below: private displayUserInfo(): any { let connect = this.connect(); connect.connect(function(err: any) { if (err) throw err; ...

Create a union type by utilizing indices of an array type

For instance: type BasicTheme = { name: 'basic'; colors: [string, string]; }; type AdvancedTheme = { name: 'advanced'; colors: [string, string, string, string]; }; type MainColor = ???; // 'main-1' | 'main-2&apo ...

Using TypeScript in .cshtml Razor Files

Recently, I embarked on a new project utilizing the ASP.NET-MVC framework. For this particular project, I decided to opt for TypeScript over JavaScript. While Visual Studio provides excellent support for TypeScript, I encountered some compatibility issues ...

What does the TypeScript error "unable to assign to parameter of type never" mean?

The code snippet is as follows: const foo = (foo: string) => { const result = [] result.push(foo) } An error in TypeScript occurs, stating: [ts] Argument of type 'string' is not assignable to parameter of type 'never'. I need h ...

Is "This" sufficient as the return type in TypeScript?

During my experimentation with method chaining, I discovered that it is possible to use "this" as a return type. How interesting! Let's take a look at an example: class Shape { color: String; setColor(value: string): this { //Shape won&apos ...

Tips for successfully passing and utilizing multidimensional arrays as props in a React component

I'm looking to pass a multidimensional array as a prop to a React component. I've successfully done this with a single-dimensional array like so: const priceTableRow = { term: '12 Months', nonRecurringCost: 820.0, monthlyRecurrin ...

Encountering an issue while defining a parameter in an Angular component: expecting either a property

Encountering an issue when attempting to set a parameter involving numbers first, as required by openweathermap's API. Specifically, the data retrieval for rain is labeled as '3h', thus requiring me to input 'data.rain.3h'. However ...

How can one effectively utilize TypeScript with native JavaScript methods and calls?

After a long break from TypeScript, I am struggling to override implementations or use native methods in the .ts file. The ones highlighted in red, excluding this, are causing errors. https://i.sstatic.net/WhcRM.png I'm not getting autocomplete sup ...

TypeScript is unable to recognize files with the extension *.vue

Can someone assist me with an issue I'm facing in Vue where it's not detecting my Single File Components? Error message: ERROR in ./src/App.vue (./node_modules/ts-loader!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/Ap ...

I possess a JSON file containing a series of associative arrays that I must convert into a PHP indexed array in order to easily retrieve specific values from it

I'm struggling to convert a list of associative arrays from a JSON file into a PHP indexed array of associative arrays, and then access the values nested in those arrays. Below is the content of the JSON file: [ { "homeTeam":"tea ...