117

I'm playing with Typescript and I wonder, how to properly instantiate and declare multidimensional array. Here's my code:

class Something {
    private things: Thing[][];

    constructor() {
        things = [][]; ??? how instantiate object ???

        for(var i: number = 0; i < 10; i++) {
            this.things[i] = new Thing[];   ??? how instantiate 1st level ???
            for(var j: number = 0; j< 10; j++) {
                this.things[i][j] = new Thing();   ??? how instantiate 2nd lvl item ???
            }
        }
    }
}

Can you give me any hint about selected places?

7 Answers 7

148

You only need [] to instantiate an array - this is true regardless of its type. The fact that the array is of an array type is immaterial.

The same thing applies at the first level in your loop. It is merely an array and [] is a new empty array - job done.

As for the second level, if Thing is a class then new Thing() will be just fine. Otherwise, depending on the type, you may need a factory function or other expression to create one.

class Something {
    private things: Thing[][];

    constructor() {
        this.things = [];

        for(var i: number = 0; i < 10; i++) {
            this.things[i] = [];
            for(var j: number = 0; j< 10; j++) {
                this.things[i][j] = new Thing();
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I can't imagine, how typings are preserved here. Can you give me any examples, please?
There are 0 items in the array, so there's no value or object to type.
I guess, it should be this.things = []; in the constructor.
36

Here is an example of initializing a boolean[][]:

const n = 8; // or some dynamic value
const palindrome: boolean[][] = new Array(n)
                                   .fill(false)
                                   .map(() => 
                                     new Array(n).fill(false)
                                   );

4 Comments

shorter new Array(n).fill(new Array(n).fill(false))
@Tukkan it will not work as expected: try to modify palindrome[0][0] and see what happens... ;)
@NirAlfasi yup, I checked and it works :)
Nope! if you'll define p = new Array(n).fill(new Array(n).fill(false)) and then modify p[0][0] = true you'll see that the whole column changes instead of a single cell!
22

If you want to do it typed:

class Something {

  areas: Area[][];

  constructor() {
    this.areas = new Array<Array<Area>>();
    for (let y = 0; y <= 100; y++) {
      let row:Area[]  = new Array<Area>();      
      for (let x = 0; x <=100; x++){
        row.push(new Area(x, y));
      }
      this.areas.push(row);
    }
  }
}

3 Comments

Thanks, but not everyone is using AngularJs to write JS/TS code.
This is just standard TS code, right? What do you see as AngularJs specific? I prefer this solution with types. Thanks
@WhatWouldBeCool the answer was edited to remove AngularJs specific code
9

You can do the following (which I find trivial, but its actually correct). For anyone trying to find how to initialize a two-dimensional array in TypeScript (like myself).

Let's assume that you want to initialize a two-dimensional array, of any type. You can do the following

const myArray: any[][] = [];

And later, when you want to populate it, you can do the following:

myArray.push([<your value goes here>]);

A short example of the above can be the following:

const myArray: string[][] = []; 
myArray.push(["value1", "value2"]);

Comments

0
class Thing {};

const rowSize = 3;
const colSize = 3;

const arr: Thing[][] = new Array(rowSize).fill(
                         new Array(colSize).fill(new Thing())
                       );

Comments

0

Creating and initializing 2D Array in typescript

const colours: number[][]=[
    [255, 255, 255],
]

//initialize by variable
const blue = [0, 0, 255];

colours.push(blue);

Comments

-3

Beware of the use of push method, if you don't use indexes, it won't work!

var main2dArray: Things[][] = []

main2dArray.push(someTmp1dArray)
main2dArray.push(someOtherTmp1dArray)

gives only a 1 line array!

use

main2dArray[0] = someTmp1dArray
main2dArray[1] = someOtherTmp1dArray

to get your 2d array working!!!

Other beware! foreach doesn't seem to work with 2d arrays!

Comments

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.