Switch the dimensions of a two-dimensional array - Unable to assign a value to property '0' as it is undefined

I'm currently working on a TypeScript code that transposes an M x N matrix:

private transpose(a: number[][]): number[][] {
    let m: number = a.length;
    let n: number = a[0].length;
    let b: number[][] = [[]]; // Attempted without "[[]]"
    for (let i: number = 0; i < m; i++) {
        for (let j: number = 0; j < n; j++) {
            b[j][i] = a[i][j]; // Encountering an Error
        }
    }
    return b;
}

Unfortunately, I am facing the following error:

Uncaught (in promise): TypeError: Cannot set property '0' of undefined

Is there a correct way to initialize the 2D array?

P.S. I have already tried using for..in, but it still presents issues

Any thoughts or solutions?

Answer №1

To achieve this, follow these steps:

let newArray: number[][] = [];
for (let index1: number = 0; index1 < size; index1++) {
    newArray[index1] = [];

    for (let index2: number = 0; index2 < length; index2++) {
        newArray[index1][index2] = originalArray[index2][index1];
    }
}

The process entails initializing an array and then creating a nested array in each iteration of the loop.

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

Type 'Object' cannot be assigned to type 'Produit' as per error code TS2322

As a newcomer to Angular, I've been encountering the following error for the past 5 days: "ERROR in src/app/modifier-produit/modifier-produit.component.ts(23,7): error TS2322: Type 'Object' is not assignable to type 'Produit'. Th ...

What could be causing the malfunction of getter/setter in a Vue TypeScript class component?

Recently delving into the world of vue.js, I find myself puzzled by the unexpected behavior of the code snippet below: <template> <page-layout> <h1>Hello, Invoicer here</h1> <form class="invoicer-form"> ...

JavaScript error: Property 'includes' of undefined cannot be accessed

To verify the existence of data.objectId in the array msgArr, I am utilizing the following code snippet: var exists = msgArr.some(item => item.objectId === data.objectId); if(!exists){ msgArr.push({"objectId":data.objectId,"latLont":data.latLont," ...

How to extract a specific property from data using Angular's HttpClient-subscribe

It seems like this question has been asked before, but I can't seem to find the answers or know what terms to search for. I have a JSON file structured like this: { "pages": [{ "displayname": "PageA", "url": "http://google.de", " ...

Deciphering a wildcard inclusion within an array

Why is this code successful: $VideoExtensions = @('.mp4','.mov','.mpg','.mts','.3g2','.3gp','.avi','.mkv','.flv','.wmv') $Files = Get-ChildItem -LiteralPat ...

When using var_dump, it will display the output as a string with the characters "**" inside double quotes, representing an array

When using a foreach loop and var_dump, I am encountering an issue where the output includes a pre-pended "string()" and quotation marks. How can I remove these unwanted characters? $dir = 'url/dir/dir/'; $images_array = glob($dir.'*.jp ...

Unforeseen dimensions have altered the np.array shapes

Working with arrays in Python has brought up many questions for me... 1) I've been creating lists of lists by reading 4 columns from N files and storing 4 elements N times in a list. After converting this list into a numpy array: s = np.array(s) I ...

Instructions for assigning a key and value within a MongoDB array

I am managing a group of students who can establish friendships with other students. {name:'someone', email:'st', friends[ObjectId,ObjectId]} When I need to access the list of friends, I have to populate the object and search through ...

Using Swift to encode arrays with NSCoder

Currently, I am working on implementing the NSCoder feature, but I have encountered a persistent issue. My main objective is to save an array of strings using NSCoder to a local file and then load it when the app is reopened. Below is the class I have cre ...

An error was encountered while trying to use the 'export' token in lodash-es that was not

Transitioning from lodash to lodash-es in my TypeScript project has been a challenge. After installing lodash-es and @types/lodash-es, I encountered an error when compiling my project using webpack: C:\..\node_modules\lodash-es\lodash. ...

Backend not receiving the request

While all tests pass successfully in Postman, I'm encountering an issue where requests are not reaching the backend when testing from the front-end. import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common ...

Utilizing WebWorkers with @mediapipe/tasks-vision (Pose Landmarker): A Step-by-Step Guide

I've been experimenting with using a web worker to detect poses frame by frame, and then displaying the results on the main thread. However, I'm encountering some delays and synchronization issues. My setup involves Next.js 14.0.4 with @mediapip ...

Determining if an object aligns with a specific type in Typescript

Hey there, I've got a little dilemma. Imagine I have a type called A: type A = { prop1: string, prop2: { prop3: string } } Now, let's say I'm getting a JSON object from an outside service and I need to check if that JSO ...

Resolve incorrect import paths in VS Code for libraries

In my Angular library, which I have packaged and published to my company's internal npm repository, I have created models that are used within the library's components. An example of one of these models is shown below: export class AdsToolbarMenu ...

Running Protractor in Components: A Comprehensive Guide

Protractor is commonly known as a testing framework, and I am currently utilizing Angular 2 for my application. I am interested in incorporating it into my app components, such as launching a browser when a button is clicked. Could you provide guidance o ...

Typescript types can inadvertently include unnecessary properties

It seems that when a class is used as a type, only keys of that class should be allowed. However, assigning [Symbol()], [String()], or [Number()] as property keys does not result in an error, allowing incorrect properties to be assigned. An even more curio ...

TypeScript declaration: discovering modules and defining namespaces

I'm currently in the process of creating a declaration file for h3. For guidance, you can refer to the function available here. Initially, I'm unsure of how typescript identifies declaration files. It seems to detect my declaration when placed ...

Angular 2 wrap-up: How to seamlessly transfer filter data from Filter Component to App Component

A filtering app has been created successfully, but there is a desire to separate the filtering functionality into its own component (filtering.component.ts) and pass the selected values back to the listing component (app.ts) using @Input and @Output functi ...

The output.library.type variable in WebPack is not defined

Currently, I am delving into WebPack with a shortcode. As part of my learning process, I am working on a code snippet that involves calculating the cube and square of a number, which are then supposed to be stored in a variable outlined in the webpack.conf ...

Error encountered when passing an argument to a call that does not accept any arguments, specifically within nested structs

Hey everyone, I have a function that requires specific parameters to be passed in. Here is how I structured the parameters: let params = [ "inputParameters" : ["A2":"a1","B1":"b1","C1& ...