Home > OS >  How to add data in jagged array in typescript?
How to add data in jagged array in typescript?

Time:12-29

I wanted to add data in someArray[][] where same data expected is like - [["xyz",123,1.23],["abc",234,2.34],etc]. I've declared some array and initialized it as - someArray: any[][] = [[]]; When I'm trying to push into someArray using for loop, I'm getting error as - 'Cannot read properties of undefined (reading 'push')'. I'm trying to push like this - someArray[i].Push(property1, property2,etc) using for loop. Can someone suggest how to push into this jagged array?

CodePudding user response:

Just write push instead of Push

CodePudding user response:

You are creating multi dimensional Array there for you need to specify each of the rows and columns before entering values to the multi dimensional array.

Please find the working attached stackblitz here.

In component.ts :

import { Component, ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  private someArray: any[][];

  constructor() {
    this.someArray = [];
    this.printArray()
  }

  printArray() {
    for (var i: number = 0; i < 10; i  ) {
      this.someArray[i] = [];
      for (var j: number = 0; j < 2; j  ) {
        if (j == 1) {
          this.someArray[i][j] = 'XXX';
        } else {
          this.someArray[i][j] = 'ZZZ';
        }
      }
    }
    console.log(JSON.stringify(this.someArray));
  }
}

in component.html :

<h4>Sample multi dimensional array</h4>
<p>
  <b>{{ someArray | json }}</b>
</p>
  • Related