Tips for rectifying a two-dimensional array mapping issue in TypeScript

I am currently working with Angular and facing an issue with multidimensional arrays in my typescript code. Specifically, the line

 this.selectedPartyCandidate = this.mappedSenateCandidates.map(_ => 0); //has issues
is causing an error while
this.selectedPartyArray = this.parties.map(_ => 0); //working
works fine with single-dimensional arrays. How can I resolve this problem related to multidimensional arrays?

Error: Type 'number[]' is not assignable to type 'number[][]'. Type 'number' is not assignable to type 'number[]'.

.ts file

 interface Candidate {
      id?: Number,
      name: string,
      party: string,
      preferences: Array<Number>
    }
    interface Party {
      party: String,
      preferences: Array<Number>
    }
    
    interface SenateCandidate {
      id: Number,
      attributes: senateCandidateAttributes
    }
    
    interface senateCandidateAttributes {
     
      updatedAt: String
    }
    
    interface mappedSentateCandidate {
      party: String
      candidates: Array<String>
    }
     
    
        constructor() {
            this.selectedPartyArray = this.parties.map(_ => 0); //working
            this.selectedPartyCandidate = this.mappedSenateCandidates.map(_ => 0); //has issues
          }
        
          selectedPartyArray: number[] = [];
          selectedPartyCandidate: number[][] = [];

.html file

<div *ngFor="let party of parties; index as index">
  <div class="column">
    <mat-form-field appearance="fill" style="max-width: 50px">
      <mat-label></mat-label>
      <mat-select (selectionChange)="preferenceChange($event, party)"  [(ngModel)]="selectedPartyArray[index]" name="preference">
        <mat-option
        *ngFor="let preference of party.preferences" 
        [value]="preference"
        >
        {{preference}}
        </mat-option>
      </mat-select>
    </mat-form-field>
  </div>
  <div class="column"></div>
  <div class="column">
    {{ party.party }}
  </div>
</div>

<p>
  <!-- Submit button -->
  <button mat-raised-button (click)="submit()">Submit</button>
</p>
<div class="flex-container">
  <div *ngFor="let mappedSenateCandidate of mappedSenateCandidates; index as index">
    <!-- <div class="column" *ngFor="let i = 1; i <= mappedSenateCandidate.length; i++">
      {{`${mappedSenateCandidate}_${i}`}}
    </div> -->
    <div>
      <div><b>{{mappedSenateCandidate.party}}</b></div>
      <div class="inner-flex-container" *ngFor="let candidate of mappedSenateCandidate.candidates; index as index1">
        <mat-form-field appearance="fill" style="max-width: 50px">
          <mat-select [(ngModel)]="selectedPartyCandidate[index][index1]" name="preference">
            <mat-option
              *ngFor="let preference of senateCandidatePrefereneList"
              [value]="preference"
              >{{ preference }}
            </mat-option>
          </mat-select>
        </mat-form-field>
        {{candidate}}
        <div></div>
      </div>
    </div>
  </div>
</div>

Answer №1

this.chosenCandidate = this.arrangedCandidates.map(_ => 0);

this.arrangedCandidates.map(_ => 0)
will generate a sequence of numbers, however this.chosenCandidate requires an array of arrays, thus it cannot be assigned with a number array. To assign an array of empty arrays, use the following:

this.chosenCandidate= this.arrangedCandidates.map(_ => []);

If you want each sub-array to contain a single 0, then use this code instead:

this.chosenCandidate = this.arrangedCandidates.map(_ => [0]);

If you wish for each sub-array to contain the same number of 0's as the original subarray elements, do the following:

this.chosenCandidate = this.arrangedCandidates.map(
  subArray => subArray.map(_ => 0)
);

Alternatively, if you prefer a one-dimensional array of numbers, modify the type of this.chosenCandidate:

chosenCandidate: number[] = [];

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

Searching for a foolproof oauth framework that includes efficient refresh tokens

Currently, I am implementing oauth with refresh tokens for my Angular application and have a specific set of requirements: Automatically refresh the token when 5% of its time is remaining Handle situations where there is a loss of internet connection (re ...

Having trouble getting the Angular2 QuickStart npm start command to function as expected

https://i.sstatic.net/CoJXX.png I have encountered an issue with the new Angular2 beta release. I am unable to follow the steps outlined in the official tutorial on their site ( https://angular.io/guide/quickstart ). If anyone has faced a similar problem ...

When executing npm run build, the fonts are not displayed properly in Vite

I'm running 'npm run build' to compile my project, and then I use the 'npm run preview' command to view it. However, some images that I've set as background images in my SCSS file are not showing up. The same issue occurs with ...

Sending a Thunk to the store using Typescript

Within my primary store.ts file, the following code is present: const store = createStore( rootReducer, composeWithDevTools(applyMiddleware(thunk)) ); store.dispatch(fetchUser()); Upon initial rendering, an action is dispatched to fetchUser in ord ...

Transform the dynamic JSON format into a key-value pair structure with nested children nodes

Looking to convert a dynamic JSON structure into a tree node: { "video": { "width": 1920, "height": 1080, "video_codec": "H264", "CBR": "4337025", "frame_rate& ...

Error: Virtual script not located; possibly absent <script lang="ts" / "allowJs": true / within the jsconfig.json.volar

https://i.sstatic.net/dFaVQ.png I noticed an error in my footer component in VueJs (TypeScript template) as depicted by the image showing blue squiggly lines. ...

Update the Angular material table with the set filtered results

Currently, I have a functioning Angular Material table with search capabilities. However, I am encountering an issue. The problem lies in the fact that when I navigate from 'route A' to 'route B' and pass a value to the search box in t ...

Seamless database migrations using sequelize and typescript

I've been exploring the concept of generating migration files for models that already exist. When I use the "force: true" mode, tables are automatically created in the database, so I find it hard to believe that creating migration files automatically ...

Navigating in Angular2 - Altering query parameters on the same page

In my project using Angular 2, I am working on a Component with a datatable that supports paging and sorting. My goal is to update the URL Parameters every time the table page/size and sorting change. When accessing this component via the Router, I also w ...

What is the best way to extract and utilize the value of an item in ngFor from a different element?

Element presented below: <div *ngFor="let item of items |xxxx ; let l = count "> <div> <!--use {{l}} in other element--> Is there a way to access the value of {{ l }} outside of this div or directly in the component.ts file after app ...

Encountering the ObjectUnsubscribedErrorImpl while utilizing angular datatable with angular version 7

I am encountering an issue when trying to display a DataTable in a modal window. Initially, everything works as expected and I can see the screen perfectly. However, after closing the modal window and opening it again, the DataTable no longer shows the sea ...

Angular - organizing information together

After retrieving the data from the database using JSON, here is the format in which it was received. var data = [ { "view_id": "999999999", "month" : 01, "year" : 2017, "visit" : 2000 }, { "view_id": "999999999", "month" ...

Create and save data to a local file using Angular service

I am facing an issue with my Angular service: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { person } from '../interfaces/iperson ...

Using the novalidate attribute in Angular 4.0.0

Since migrating to angular 4, I have encountered a peculiar issue with my template-driven form. The required attribute on the input field appears to be malfunctioning. It seems like the form has the novalidate attribute by default, preventing HTML5 validat ...

Is there a way to ensure that the await subscribe block finishes before moving on to the next line of code?

My goal is to utilize the Google Maps API for retrieving coordinates based on an address. In my understanding, using await with the subscribe line should ensure that the code block completes before moving on to the subsequent lines. async getCoordinates ...

What is preventing my Angular form from displaying the input data correctly?

I've been diligently following a PDF tutorial step by step, but for some reason, I'm not achieving the same results. Despite thorough googling, I can't seem to figure out where I'm going wrong. Here's the content of student.compon ...

Creating nested Angular form groups is essential for organizing form fields in a hierarchical structure that reflects

Imagine having the following structure for a formGroup: userGroup = { name, surname, address: { firstLine, secondLine } } This leads to creating HTML code similar to this: <form [formGroup]="userGroup"> <input formCon ...

typescript exploring the versatility of dynamic types and generics

Understanding TypeScript dynamic and generic types can be challenging for me. The goal is to create a function that generates an object with a specific type, where some properties of the object must match the parameters provided to the function. Essentia ...

Can the User Pool name be changed in AWS Cognito after it has been created?

I'm currently working on updating the User Pool name and User attributes in AWS Cognito using my code. While I have been able to gather information on updating user attributes, I haven't come across anything specific about changing the pool name ...

How can you load a chosen list in Angular's Mat Selection List component?

I populated my selection list with a list of items. How can I specify which item should be selected in the list after it has been loaded? Here is the HTML code snippet: <div class="col-md"> <div class="form-group"> ...