JavaScript Multidimensional Arrays

A JavaScript multidimensional array is an array of arrays, or, in other words, an array whose elements consist of arrays. We demonstrate with the following multidimensional array:

var ar = [
    ['apple', 'orange', 'pear'],
    ['carrots', 'beans', 'peas'],
    ['cookies', 'cake', 'muffins', 'pie']
];

How to Access Elements of a Multidimensional Array

To access elements of the nested arrays, use square brackets as the following demonstrates:

alert( ar[2][1] ); // cake

The first square bracket references the desired element in the outer array. The second square bracket references the desired element in the inner array. So ar[2][1] references the second element in the third sub-array. (JavaScript array indexes start at zero.)

Adding and Removing Elements in Multidimensional Arrays

You can use square bracket notation to add elements to the inner arrays. The following demonstrates adding a new element at the end of the first sub-array, with console.log used to display the result:

ar[0][3] = 'banana';
console.log( ar[0] ); // ["apple", "orange", "pear", "banana"]

You can apply array methods to the nested arrays. Here we use the push method to add two new elements to the second sub-array:

ar[1].push('kale', 'broccoli');
console.log( ar[1] ); // ["carrots", "beans", "peas", "kale", "broccoli"]

Here we demonstrate using the push method to add a new array element to the outer array:

ar.push( ['fried chicken', 'pot roast', 'rib-eye steak'] );

You can also use array methods to remove elements from sub-arrays, as we demonstrate here with the pop method:

ar[2].pop(); // remove last element from 3rd sub-array
alert( ar[2] ); // cookies,cake,muffins 

Find out more about methods to add and remove array elements.

Looping through Multidimensional Arrays

When you want to iterate over the elements of a multidimensional array, use nested for loops:

// outer loop applies to outer array
for (var i=0, len=ar.length; i<len; i++) {
    // inner loop applies to sub-arrays
    for (var j=0, len2=ar[i].length; j<len2; j++) {
        // accesses each element of each sub-array in turn
        console.log( ar[i][j] ); 
    }
}

Notice the variables initialized and used by each for loop, i.e., the counter variables (i and j) and test expressions (len and len2). The inner loop iterates through each element (ar[i][j]) in the current sub-array (ar[i]); console.log is used to display the value of each element in turn.