Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How do I create an empty 2D array in Javascript (without knowing how many rows or columns there will be in the new array)?

If it's a simple array var newArray = new Array(); I can assign as many elements as I want. But what about a 2D array? Can I create one without specifying the numbers of rows and columns? and how do I access the elements afterwards (myArray[0][1] or myArray[0,1])?

share|improve this question
1  
duplicate of: stackoverflow.com/questions/6495187/… stackoverflow.com/questions/7521796/… and many more –  K_B May 12 '13 at 21:24
    
I assumed that var row_major = Array(height).map(function () { return Array(width); }); would do the trick, but finally needed a 2D array today and found that it doesn't. Damn. –  Mark K Cowan Jun 11 '14 at 18:51

3 Answers 3

up vote 4 down vote accepted

Yes you can create an empty array and then push data into it. There is no need to define the length first in JavaScript.
Check out jsFiddle Live Demo

Define:

var arr = new Array([]);

Push data:

arr[0][0] = 'Hi data';

Read data:

alert(arr[0][0]);
share|improve this answer
    
and how do we define it then new Array ()()? –  meks May 12 '13 at 21:31
    
@meks Like this: new Array([]), Check Out the demo. Did the answer solve your problem ? –  Siamak A.Motlagh May 12 '13 at 21:46

There are no two dimensional arrays in Javascript.

To accomplish the effect of a two dimensional array, you use an array of arrays, also known as a jagged array (because the inner arrays can have different length).

An empty jagged array is created just like any other empty array:

var myArray = new Array();

You can also use an empty array literal:

var myArray = [];

To put any items in the jagged array, you first have to put inner arrays in it, for example like this:

myArray.push([]);
myArray[0][0] = 'hello';

You can also create an array that contains a number of empty arrays from start:

var myArray = [[],[],[]];

That gives you a jagged array without any items, but which is prepared with three inner arrays.

As it's an array of arrays, you access the items using myArray[0][1].

share|improve this answer
    
Thanks This is very helpfull –  meks May 12 '13 at 23:34
var myArray = [
    ["cats","dogs","monkeys","horses"],
    ["apples","oranges","pears","bananas"]
];
document.write(myArray[0][2]) //returns "monkeys"
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.