Declare an empty two-dimensional array in Javascript?

322,629

Solution 1

You can just declare a regular array like so:

var arry = [];

Then when you have a pair of values to add to the array, all you need to do is:

arry.push([value_1, value2]);

And yes, the first time you call arry.push, the pair of values will be placed at index 0.

From the nodejs repl:

> var arry = [];
undefined
> arry.push([1,2]);
1
> arry
[ [ 1, 2 ] ]
> arry.push([2,3]);
2
> arry
[ [ 1, 2 ], [ 2, 3 ] ]

Of course, since javascript is dynamically typed, there will be no type checker enforcing that the array remains 2 dimensional. You will have to make sure to only add pairs of coordinates and not do the following:

> arry.push(100);
3
> arry
[ [ 1, 2 ],
  [ 2, 3 ],
  100 ]

Solution 2

If you want to initialize along with the creation, you can use fill and map.

const matrix = new Array(5).fill(0).map(() => new Array(4).fill(0));

5 is the number of rows and 4 is the number of columns.

Solution 3

ES6

Matrix m with size 3 rows and 5 columns (remove .fill(0) to not init by zero)

[...Array(3)].map(x=>Array(5).fill(0))       

let Array2D = (r,c) => [...Array(r)].map(x=>Array(c).fill(0));

let m = Array2D(3,5);

m[1][0] = 2;  // second row, first column
m[2][4] = 8;  // last row, last column

// print formated array
console.log(JSON.stringify(m)
  .replace(/(\[\[)(.*)(\]\])/g,'[\n  [$2]\n]').replace(/],/g,'],\n  ')
);

Solution 4

If you want to be able access the matrix like so:

matrix[i][j]

I find it the most convenient to init it in a loop.

var matrix = [],
    cols = 3;

//init the grid matrix
for ( var i = 0; i < cols; i++ ) {
    matrix[i] = []; 
}

This will give you

[ [], [], [] ]

so

matrix[0][0]
matrix[1][0]

returns undefined and not the error "Uncaught TypeError: Cannot set property '0' of undefined".

Solution 5

You can nest one array within another using the shorthand syntax:

   var twoDee = [[]];
Share:
322,629
Zannix
Author by

Zannix

Updated on February 01, 2022

Comments

  • Zannix
    Zannix over 2 years

    I want to create a two dimensional array in Javascript where I'm going to store coordinates (x,y). I don't know yet how many pairs of coordinates I will have because they will be dynamically generated by user input.

    Example of pre-defined 2d array:

    var Arr=[[1,2],[3,4],[5,6]];
    

    I guess I can use the PUSH method to add a new record at the end of the array.

    How do I declare an empty two dimensional array so that when I use my first Arr.push() it will be added to the index 0, and every next record written by push will take the next index?

    This is probably very easy to do, I'm just a newbie with JS, and I would appreciate if someone could write a short working code snippet that I could examine. Thanks