Multi-dimension arrays in JavaScript

This tutorial will explain how to create, access, and modify elements in a multi-dimension array. In the example here, we will work with a 2D (two-dimension) array in JavaScript.

We already know that an array is one way of storing several related values in one data structure (storing several pieces of information in one array, rather storing information across multiple variables). For example, we could store all of the different characteristics about a person (such as name, age, location) within an array. But…what if we wanted to store several characteristics for several different people in one structure? Well, we could use a two-dimension array for that! This involves creating arrays to store the information about each person and all of these arrays are actually elements in another array.

Watch the video below to find out more and then scroll down to see the sample code.

In the example code below, we have a two-dimension array that stores several people in the array. For each person, the array also stores characteristics about them including their name, age, and location. In other words, there are elements inside elements in the array.

If we wanted to access the first element in an array we would usually use the code arrayname[0]. If we want to access the first element inside the first element of the array, we would access it using the code arrayname[0][0]. Basically, there are two dimensions in the array. We access the first element in the first dimension and the first element from its second dimension.

Check out the code below to see how you can create a 2D array, access elements inside it, and modify values in the array.

Here is the HTML code:

<html>
    <head>
        <title>Multi-dimension arrays</title>
        <script src="script.js"></script>
    </head>
        
    <body>

    </body>
</html>

And here is the JavaScript code:

// This creates a two-dimension array
// Here there are three arrays within the people array
var people = [
    ["Joe", 16, "Sydney"], // 0
    ["Alice", 20, "Melbourne"], // 1
    ["Jack", 15, "Brisbane"], // 2
];

// This will display the second element from the second array with the people array (Alice's age)
console.log(people[1][1]);

// This will update the second element in the third array in the people array (Jack's age)
people[2][1] = 16;

// This will display the third array in the people array (all information about Jack)
console.log(people[2]);

// This will add a fourth array to the people array
people[3] = ["Sally", 30, "Perth"];

// This will display all elements from the people array
console.log(people);

We will also look at JSON (another method of organising data) later in this tutorial series which can be a better way of organising data and giving it more structure.

Next tutorial: If statements