Multi-dimensional arrays
Coding with JavaScript
🕑 This lesson will take about 10 minutes
In this lesson, you will learn how to create, access, and modify elements in a multi-dimensional 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.
Sample HTML & JavaScript code
Next lesson: Objects