JavaScript: Creating 2-Dimensional or Multidimensional Arrays

How to create 2-Dimensional or Multidimensional Arrays in JavaScript.

Creating 2-Dimensional/Multidimensional Arrays in JavaScript

You may want to read my article on single arrays first at here.

In JavaScript, we create multidimensional arrays by creating an array of arrays. As we can create an array and add mixtures of types such as strings, numbers or objects, such as:

var arr = ['red', 123, arr3];

then we can create a 2-dimensional array by just adding arrays:

var arr1 = [ 
             ['clubs', 'hearts', 'spades'], 
             ['ace', 'two', 'three' ], 
             ['red', 'blue', 'green'] 
           ];

arr1.length is 3.

You access the array with numerical indexes in the format [][].

var x = arr1[0][0]; // 'clubs'
var y = arr1[2][1]; // 'blue'

If you try to read outside the boundaries of the array you will get undefined.

JavaScript arrays are Jagged arrays (also called ragged arrays) meaning they can be mixed types and length. So the dimensions do not have to be equal length. You don’t even have to use the next index. Consider:

arr1[1][4] = 'five';

Now our array looks like:

[ 
  ['clubs', 'hearts', 'spades'], 
  ['ace', 'two', 'three', undefined, 'five' ],
  ['red', 'blue', 'green'] 
]

The lengths change accordingly

var len1 = arr1[0].length; // 3
var len2 = arr1[1].length; // 5

This auto-creation of additional elements can be useful but it is also dangerous in that it is easy to inadvertently extend an array and the problems caused can be difficult to debug.

Larger Arrays

Creating arrays by initialisation is OK for small arrays, but tedious if not impractical for larger arrays. You can use var arr = [] and then use a nested loop to create the arrays/elements required, but a quicker way is to use the array.fill() method which fills the entire array with a value or a new array. For example:

var arr2 = new Array(3).fill(new Array(3));

would create

[ 
  [undefined, undefined, undefined],
  [undefined, undefined, undefined],
  [undefined, undefined, undefined]
]

or you can repeat the command and initialise the values too:

var arr3 = new Array(3).fill(new Array(3).fill("0"));

[ 
  ["0", "0", "0"], 
  ["0", "0", "0"], 
  ["0", "0", "0"] 
]

Summary

JavaScript can create multidimensional arrays. Some purists may argue that these are not true multidimensional arrays but they’re usually good enough for most coders. Ensure that you understand how they work and if in doubt use the browser F12 tools to see what you have actually created and check its properties.