2

I have declared a two-dimensional array, like so:

a = [[]]

However, when I try to give a second dimension value using a first dimension index other than 0, it doesn't work:

a[1][0] = "foo" //returns error

Is there a better way around this than manually defining every index you need as an array, i.e.:

a[1] = [];
a[2] = [];
a[3] = [];
//et cetera
Bluefire
  • 13,519
  • 24
  • 74
  • 118

6 Answers6

8

N-Dimensional arrays do not exist in javascript - you have to just make arrays containing arrays as elements.

You're getting an error because a = [[]]; declares an array with one element, which happens to also be an array. Therefore a[0] is the internal array, but a[1] does not exist because you never declared it. The easiest way to properly declare a "two dimensional array" would be to use a loop:

var outerArray = [];
var numInternalArrays = 5;
for (var i = 0; i < numInternalArrays; i++) {
    outerArray[i] = [];
}
jbabey
  • 45,965
  • 12
  • 71
  • 94
5

If you know how many elements the root array should have you could do something like this:

var arr = 
    (Math.pow(2,10)-1).toString(2)  // Binary string of 1s. Its length being 10
    .split('')                      // Create an array from this string
    .map(function(){return [];});   // Map a new empty array to each index

console.log(arr);                   // [[],[],[],[],[],[],[],[],[],[]]

This accomplishes the same thing:

for(var arr = [], i=10; i--; arr[i]=[]);

No need to declare arr outside of the for-loop since javascript doesn't have block scope, it will be added to the scope in which it is executed.

Shmiddty
  • 13,847
  • 1
  • 35
  • 52
  • 3
    This is the best answer ever, I did not understand JavaScript prior to reading this and not I do. I used to be a miserable being with no respect to my elders, I have now found the said respect. Thank you Shmiddty, thank you for turning my life around! Your deed will not go unnoticed! – Benjamin Gruenbaum Oct 06 '14 at 16:24
  • 1
    Can you maybe also provide an answer using jQuery? I hear it's really good and solves these issues better. – Benjamin Gruenbaum Oct 06 '14 at 16:26
  • 2
    The clarity of my life has been increased tenfold by reading this answer. – Sterling Archer Oct 06 '14 at 16:26
  • 2
    This answer has cured my SPD, thank you for giving me a second change Shmiddty, I won't waste it! Truly inspiring. – little pootis Oct 06 '14 at 16:30
4
a = [[]]

This is an Array, with the first item being an array. Which is why indexing into the first item still works (a[0][0]).

If you want to access the second item as an array, you need to create your array as

a = [[],[]]

See this question for examples of How can I create a two dimensional array in JavaScript?

Community
  • 1
  • 1
Zeph
  • 1,728
  • 15
  • 29
2

If I understand correctly, use a loop:

for (var i = y; i--; a[i] = []);
David G
  • 94,763
  • 41
  • 167
  • 253
  • My bad again: I meant to say if there's another way around it than defining all of them in whatever way. I was wondering if there's a magic trick in JS that does it for you. – Bluefire Jan 24 '13 at 20:38
  • @Bluefire I still don't entirely understand what you're trying to do. Does my answer not help? – David G Jan 24 '13 at 20:41
  • It does, I was just wondering if there was a native function that would do the trick. – Bluefire Jan 24 '13 at 20:43
  • @Bluefire Nope, there's not. Once you add this line of code then you can do `a[1][0] = "foo"` without error. – David G Jan 24 '13 at 20:44
  • @David you can declare `a` in the loop as well, though it might be less readable. – Shmiddty Jan 24 '13 at 21:48
1

There are no multidimensional arrays in javascript.
What you are doing is an array of arrays, but the outermost array has only one element (i.e. element 0) whose value is another array. So a[1] (or more generally a[1][x]) is invalid since the outermost array has only one element.
So you can do a[0][x] = "foo" but not the other way around.

So you can either initialize the array with a for loop or do something like var a =[[][][][][]];

pakman
  • 1,676
  • 3
  • 23
  • 41
1

You can have the array of arrays start as in:

var a = []; // start with the column array

Then when you want to put something in location [i][j] we can call 'i' the row-index and 'j' the column-index.

if (!a[i]) {   // check for row existing
    a[i] = []; // .. and create it if not 
}
a[i][j] = 'foo'; // put something in the array cell

Note that this only works because we are always putting something in the new row array right after we create it. It might not work if you put 0 or "" in there instead of 'foo'.

There are a lot of things in javascript that are 'false' including 'null' and 'undefined' and '0' and I just don't know if an empty array or an array with one element that is an empty string are considered false. So you would have to do some experimenting with how, exactly to detect a missing row array so you can add it in.

Lee Meador
  • 12,829
  • 2
  • 36
  • 42