Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare an empty two-dimensional array in Javascript?

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

like image 744
Zannix Avatar asked Aug 10 '13 15:08

Zannix


People also ask

How do you write an empty array in JavaScript?

We can also explicitly check if the array is empty or not. if (arr. length === 0) { console. log("Array is empty!") }

How do you declare an empty 2D array in Java?

To create an empty array, you can use an array initializer. The length of the array is equal to the number of items enclosed within the braces of the array initializer. Java allows an empty array initializer, in which case the array is said to be empty.


2 Answers

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 ] 
like image 170
DJG Avatar answered Sep 30 '22 20:09

DJG


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.

like image 23
AbhinavD Avatar answered Sep 30 '22 20:09

AbhinavD