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.

I have been reading online and some places say it isn't possible, some say it is and then give an example and others refute the example, etc.

  1. How do I declare a 2 dimensional array in JavaScript? (assuming it's possible)

  2. How would I access its members? (myArray[0][1] or myArray[0,1]?)

Thanks

share|improve this question
 
possible duplicate of How to create a multi dimensional array in Javascript? –  Anderson Green Jul 20 '13 at 19:51
 
Who voted to close this question? The question that it points to is merely a cross link. –  Lion Jul 21 '13 at 19:55
add comment

13 Answers

up vote 315 down vote accepted
var items = [[1,2],[3,4],[5,6]];
alert(items[0][0]); // 1
share|improve this answer
5  
The easiest example so far :) +1 –  itsols Jul 17 '12 at 3:49
4  
It would be difficult to initialize a large multidimensional array this way. However, this function can be used to create an empty multidimensional, with the dimensions specified as parameters. –  Anderson Green Apr 6 '13 at 16:49
add comment

You simply make each item within the array an array.

  var x = new Array(10);
  for (var i = 0; i < 10; i++) {
    x[i] = new Array(20);
  }
  x[5][12] = 3.0;
share|improve this answer
4  
Can they use things like strings for their keys and values? myArray['Book']['item1'] ? –  Diego Jun 8 '09 at 19:54
11  
@Diego, yes, but that's not what arrays are intended for. It's better to use an object when your keys are strings. –  Matthew Crumley Jun 8 '09 at 20:05
add comment

Similar to activa's answer, here's a function to create an n-dimensional array:

function createArray(length) {
    var arr = new Array(length || 0),
        i = length;

    if (arguments.length > 1) {
        var args = Array.prototype.slice.call(arguments, 1);
        while(i--) arr[length-1 - i] = createArray.apply(this, args);
    }

    return arr;
}

createArray();     // [] or new Array()

createArray(2);    // new Array(2)

createArray(3, 2); // [new Array(2),
                   //  new Array(2),
                   //  new Array(2)]
share|improve this answer
 
Can this create a 4 dimensional array? –  trusktr May 19 '11 at 2:18
 
@trusktr: Yes, you could create as many dimensions as you want (within your memory constraints). Just pass in the length of the four dimensions. For example, var array = createArray(2, 3, 4, 5);. –  Matthew Crumley May 19 '11 at 4:21
 
Nice! I actually asked about this here: stackoverflow.com/questions/6053332/javascript-4d-arrays and a variety of interesting answers. –  trusktr May 19 '11 at 5:50
add comment

The reason some say that it isn't possible is because a two dimensional array is really just an array of arrays. The other comments here provide perfectly valid methods of creating two dimensional arrays in JavaScript, but the purest point of view would be that you have a one dimensional array of objects, each of those objects would be a one dimensional array consisting of two elements.

So, that's the cause of the conflicting view points.

share|improve this answer
22  
No, it's not. In some languages, you can have multidimensional arrays like string[3,5] = "foo";. It's a better approach for some scenarios, because the Y axis is not actually a child of the X axis. –  Rafael Soares Aug 4 '11 at 15:29
add comment

Javascript only has 1-dimensional arrays, but you can build arrays of arrays, as others pointed out.

The following function can be used to construct a 2-d array of fixed dimensions:

function Create2DArray(rows) {
  var arr = [];

  for (var i=0;i<rows;i++) {
     arr[i] = [];
  }

  return arr;
}

The number of columns is not really important, because it is not required to specify the size of an array before using it.

Then you can just call:

var arr = Create2DArray(100);

arr[50][2] = 5;
arr[70][5] = 7454;
// ...
share|improve this answer
add comment

Two dimensional arrays are created the same way single dimensional arrays are. And you access them like array[0][1].

var arr = [1, 2, [3, 4], 5];

alert (arr[2][1]); //alerts "4"
share|improve this answer
add comment

The easiest way:

var myArray = [[]];
share|improve this answer
3  
This simply creates an empty 1x1 array. –  Anderson Green Apr 6 '13 at 16:46
2  
which is a 2-dimension array –  Maurizio In denmark Jul 2 '13 at 13:07
2  
thanks for that. I was looking exactly this to define an array –  AmitKB Jul 22 '13 at 13:31
add comment

I'm not sure if anyone has answered this but I found this worked for me pretty well -

var array = [[,],[,]]

eg:

var a = [[1,2],[3,4]]

For a 2 dimensional array, for instance.

share|improve this answer
 
How can I do this dynamically? I want the inner arrays with different sizes. –  Laszlo-Andras Zsurzsa Jan 19 at 16:48
add comment

Few people show the use of push:
To bring something new, I will show you how to initialize the matrix with some value, example: 0 or an empty string "".
Reminding that if you have a 10 elements array, in javascript the last index will be 9!

function matrix( rows, cols, defaultValue){

  var arr = [];

  // Creates all lines:
  for(var i=0; i < rows; i++){

      // Creates an empty line
      arr.push([]);

      // Adds cols to the empty line:
      arr[i].push( new Array(cols));

      for(var j=0; j < cols; j++){
        // Initializes:
        arr[i][j] = defaultValue;
      }
  }

return arr;
}

usage examples:

x = matrix( 2 , 3,''); // 2 lines, 3 cols filled with empty string
y = matrix( 10, 5, 0);// 10 lines, 5 cols filled with 0
share|improve this answer
add comment

You could allocate an array of rows, where each row is an array of the same length. Or you could allocate a one-dimensional array with rows*columns elements and define methods to map row/column coordinates to element indices.

Whichever implementation you pick, if you wrap it in an object you can define the accessor methods in a prototype to make the API easy to use.

share|improve this answer
add comment

I had to make a flexible array function to add "records" to it as i needed and to be able to update them and do whatever calculations e needed before i sent it to a database for further processing. Here's the code, hope it helps :).

function Add2List(clmn1, clmn2, clmn3) {
    aColumns.push(clmn1,clmn2,clmn3); // Creates array with "record"
    aLine.splice(aPos, 0,aColumns);  // Inserts new "record" at position aPos in main array
    aColumns = [];    // Resets temporary array
    aPos++ // Increments position not to overlap previous "records"
}

Feel free to optimize and / or point out any bugs :)

share|improve this answer
add comment

If you are after 2D array for google charts, the best way to do it is

var finalData = [];
[["key",value], ["2013-8-5", 13.5], ["2013-7-29",19.7]...]

referring to Not a valid 2d array google chart

share|improve this answer
add comment

The easiest way:

var arr  = [];

var arr1 = ['00','01'];
var arr2 = ['10','11'];
var arr3 = ['20','21'];

arr.push(arr1);
arr.push(arr2);
arr.push(arr3);

alert(arr[0][1]); // '01'
alert(arr[1][1]); // '11'
alert(arr[2][0]); // '20'
share|improve this answer
add comment

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.