Multidimensional/Nested Arrays in JavaScript [Guide]

Multidimensional/Nested Arrays in JavaScript

This guide aims to succinctly show you how multidimensional arrays can be created and used in the JavaScript programming language.

What are Arrays?

Arrays are a key component in any app kind of app you may wish to build – arrays allow you to store an ordered list of variables or values of any length in a single variable – ready to be iterated over, displayed, or otherwise processed.

For example, an array could contain a list of contacts for an instant messaging application, or one might contain a list of items the player has collected in a video game.

Arrays form the backbone of pretty much every program you might write in PHP or any other programming language.

Arrays are a type of variable which contain an ordered list of values. These values can be of any type, and are referred to as the elements or items in the array.

Array Indexes

As arrays are ordered, each element in the array has a numerical position which determines where in the array it appears.

This is called the indexIndexes start counting at position 0, so the first item in an array is at index 0, the second item is at index 1 and so on.

What are Multidimensional Arrays?

Arrays are one-dimensional. They’re a list of values, comparable to a single column in a table or spreadsheet

However, arrays can contain other arrays. This adds a second dimension, like adding rows to the spreadsheet in addition to the column.

This is probably better shown visually:

var oneDimensionalArray = ['a', 'b', 'c', 'd];

var twoDimensionalArray = [
    ['a1', 'a2', 'a3', 'a4'],
    ['b1', 'b2', 'b3', 'b4'],
    ['c1', 'c2', 'c3', 'c4']
];

The variable oneDimensionalArray is a single dimensional array – an array containing a list of letters.

twoDimensionalARarray however is an array containing other arrays. This can be treated like a table with rows and columns – two dimensions. I’ve formatted the declaration of the arrays into rows and columns so you can see the effect. The value b1 is located in the first column of the second row.

There is no limit to how many arrays can be nested. The number of nested arrays is referred to as the depth of the multidimensional array. A multidimensional array which has an array, inside an array, inside an array has a depth of 3 is a three dimensional array (unfortunately, after two dimensional arrays, they become a bit hard to illustrate).

What are Multidimensional Arrays used for in JavaScript?

As shown above, multidimensional arrays are most often used to represent tabulated data. Each element of the array containing the data for a single row or record.

Multidimensional arrays are also commonly used when developing video games. The grid-like nature of two dimensional arrays is perfect for building two-dimensional gameplay areas, each array element containing information on what should be placed at that grid point (a tree, the player, grass, etc). These grids could also be stacked so that game elements can appear on-top of each other, creating even more complex multidimensional arrays.

This sounds complicated, but as arrays are all indexed it makes it easy to manage what’s in them by their position.

Arrays can also be searched, re-ordered, cloned, and otherwise processed.

Declaring Multidimensional Arrays

You’ve already seen how multidimensional arrays are declared in JavaScript earlier in this article. Below, a two dimensional array is declared:

var twoDimensionalArray = [
    ['a1', 'a2', 'a3', 'a4'],
    ['b1', 'b2', 'b3', 'b4'],
    ['c1', 'c2', 'c3', 'c4']
];

Again, this is an array containing several sub-arrays. The outer array containing rows, and the sub-array containing column values.

Note that the sub-arrays in a multidimensional array do not have to be of equal size! So the below is perfectly valid:

var twoDimensionalArray = [
    ['a1', 'a2'],
    ['b1', 'b2', 'b3', 'b4'],
    ['c1', 'c2', 'c3']
];

Whether or not having different length arrays will present a problem will depend on what it is you’re trying to accomplish programmatically.

Accessing Values in Multidimensional Arrays

All arrays in JavaScript are indexed. All indexes are populated, so if an element is removed from an array, it is re-indexed so that no numbers are skipped in the list of indexes for that array.

In a single dimensional array, to access a value by it’s index you would do the following:

oneDimensionalArray[1] // Access the second value in a single dimensional array

Square brackets are used after the name of the array variable to specify the index of the element to be retrieved.

Multidimensional arrays work exactly the same way – you just specify the index of the first array, followed by the index of any sub-arrays you wish to access, until you have reached the depth of the value you wish to retrieve.

twoDimensionalArray[1][0] // Access the value on the second row (index 1), first column (index 0) from a two dimensional array

Above, two indexes are defined, the first for the outermost array in the two dimensional array shown above, and the second for the array at the second level of the array. This would retrieve the value b1.

If your array had three levels, you would simply keep specifying indexes:

threeDimensionalArray[1][0][2] // Access the value of a three dimensional array

Iterating/Looping Through Multidimensional Arrays

The JavaScript foreach() loop is used to iterate over arrays.

Multidimensional arrays, being nested arrays, can be iterated by nesting multiple foreach() loops. This is best demonstrated with a code example:

// Declare a multidimensional array
var twoDimensionalArray = [
    ['a1', 'a2', 'a3', 'a4'],
    ['b1', 'b2', 'b3', 'b4'],
    ['c1', 'c2', 'c3', 'c4']
];

// Loop through the outermost array
twoDimensionalArray.forEach(function(rowValue, rowIndex){

    // Loop through each of the sub-arrays
    rowValue.forEach(function(columnValue, columnIndex){

        // Print the index of the outer and inner arrays
        console.log('row: ' + rowIndex + ', column: ' + columnIndex); 

        // Print the value stored at the current row, column position
        console.log(columnValue);

    });
    
});

The above code will output:

row: 0, column: 0 
a1
row: 0, column: 1 
a2
row: 0, column: 2 
a3
row: 0, column: 3 
a4
row: 1, column: 0 
b1
row: 1, column: 1 
b2
row: 1, column: 2 
b3
row: 1, column: 3 
b4
row: 2, column: 0 
c1
row: 2, column: 1 
c2
row: 2, column: 2 
c3
row: 2, column: 3 
c4

Each of the sub-arrays is traversed by the first foreach() loop in order, with each element within those arrays traversed by the second foreach() loop prior to the first foreach loop moving on to the next sub-array.

Searching MultiDimensional Arrays

It is also possible to search nested/multidimensional arrays with a mix of nested loops and the built in JavaScript array search methods.

Finding the First Matching Value with the find() Method

// Declare a multidimensional array
var twoDimensionalArray = [
    ['a1', 'a2', 'a3', 'a4'],
    ['b1', 'b2', 'b3', 'b4'],
    ['c1', 'c2', 'c3', 'c4']
];

// Declare a variable to hold the search result when it is found
var found;

// Loop through the outermost array
for (const [rowIndex, rowValue] of twoDimensionalArray.entries()) {

    // Use the find() method to find the first matching value in the sub-array and assign it to the found variable
    found = rowValue.find(function(columnValue, columnIndex){
        
        if(columnValue == 'b3') {
            console.log('Found! row: ' + rowIndex + ', column: ' + columnIndex); 
            return true;
        } else {
            return false;
        }

    }); 

    // If a result has been found we can break out of the for loop as the job is done
    if(typeof found !== 'undefined') break;
    
};

console.log(found); // Confirm the result

This will output:

Found! row: 1, column: 2 
b3

There are ways to do this that require less lines of code, but this illustrates what’s going on under the hood and how the arrays are traversed.

Finding all Matching Values with the filter() Method

// Declare a multidimensional array - note there are some duplicate 'b2' values in this one!
var twoDimensionalArray = [
    ['a1', 'a2', 'a3', 'b2'],
    ['b1', 'b2', 'b3', 'b4'],
    ['c1', 'c2', 'b2', 'c4']
];

// Declare a variable to hold the search results when it is found - there may be multiple results, so it is an array
var results = [];

// Loop through the outermost array
for (const [rowIndex, rowValue] of twoDimensionalArray.entries()) {

    // Find all matching values in the sub array using the filter() function
    var found = rowValue.filter(function(columnValue, columnIndex){
        
        if(columnValue == 'b2') {
            console.log('Found! row: ' + rowIndex + ', column: ' + columnIndex); 
            return true;
        } else {
            return false;
        }

    }); 

    // Merge what was found in this iteration with the final results
    results = results.concat(found);
    
};

console.log(results); // Confirm the results

This will output:

Found! row: 0, column: 3
Found! row: 1, column: 1
Found! row: 2, column: 2
Array(3) [ "b2", "b2", "b2" ]

Which confirms that the three array elements with the value b2 from the multidimensional array were found.

Cloning/Copying Multidimensional Arrays

Cloning and copying arrays, especially multidimensional arrays, takes a bit of consideration – it’s not as simple as it appears to be in JavaScript!

I recommend reading the article linked above to find out why JavaScript arrays can’t simply be copied by assigning their value to a new variable, but if you want to just see how to do it, here it is:

var multiDimensionalArrayCopy = JSON.parse(JSON.stringify(multiDimensionalArray));

This will create a new variable, multiDimensionalArrayCopy, which will be a complete clone/copy of the variable named multiDimensionalArray.

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published. Required fields are marked *